Class: BitGirder::Core::WaitCondition

Inherits:
BitGirderClass show all
Defined in:
lib/bitgirder/core.rb

Constant Summary

Constants included from BitGirderMethods

BitGirderMethods::PARAM_TYPE_ARG, BitGirderMethods::PARAM_TYPE_ENVVAR, BitGirderMethods::PARAM_TYPE_KEY

Class Method Summary collapse

Instance Method Summary collapse

Methods included from BitGirderMethods

argv_to_argh, check_fail_prefix, class_name_to_sym, code, compares_to, console, ext_to_class_name, ext_to_sym, has_env, has_key, has_keys, nonnegative, not_nil, positive, raisef, set_from_key, set_var, split_argv, sym_to_cli_switch, sym_to_ext_id, to_bool, unpack_argv_array, unpack_argv_hash, warn

Methods included from BitGirderStructure

#==, included

Constructor Details

#initialize(f, waiter, opts) ⇒ WaitCondition

Returns a new instance of WaitCondition.



1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
# File 'lib/bitgirder/core.rb', line 1325

def initialize( f, waiter, opts )

    @f, @waiter = f, waiter
    
    raise "One of :max_tries or :max_wait must be given" unless 
        opts.key?( :max_tries ) || opts.key?( :max_wait )

    @max_tries = opts.key?( :max_tries ) ?
        positive( opts[ :max_tries ] ) : 1 << 63
    
    @max_wait = opts.key?( :max_wait ) ? 
        positive( opts[ :max_wait ] ) : Float::INFINITY
end

Class Method Details

.create_and_exec(waiter, opts, blk) ⇒ Object



1359
1360
1361
1362
1363
1364
# File 'lib/bitgirder/core.rb', line 1359

def self.create_and_exec( waiter, opts, blk )
    
    raise "No block given" unless blk

    self.send( :new, blk, waiter, opts ).execute
end

.wait_backoff(opts, &blk) ⇒ Object



1374
1375
1376
1377
1378
1379
1380
# File 'lib/bitgirder/core.rb', line 1374

def self.wait_backoff( opts, &blk )
    
    seed = positive( has_key( opts, :seed ), :seed )
    waiter = lambda { |rem| sleep( [ seed, rem ].min ); seed *= 2 }

    self.create_and_exec( waiter, opts, blk )
end

.wait_poll(opts, &blk) ⇒ Object



1366
1367
1368
1369
1370
1371
1372
# File 'lib/bitgirder/core.rb', line 1366

def self.wait_poll( opts, &blk )
    
    poll = positive( has_key( opts, :poll ), :poll )
    waiter = lambda { |rem| sleep( [ poll, rem ].min ) }

    self.create_and_exec( waiter, opts, blk )
end

Instance Method Details

#executeObject



1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
# File 'lib/bitgirder/core.rb', line 1340

def execute

    res = nil
    
    start = Time.now

    @max_tries.times do |i|

        break if res = @f.call

        remain = @max_wait - ( Time.now - start )
        break if remain <= 0

        @waiter.call( remain ) if i < @max_tries - 1
    end

    res
end