Class: Collective::Idler
- Inherits:
-
Object
- Object
- Collective::Idler
- Extended by:
- Utilities
- Defined in:
- lib/collective/idler.rb
Overview
Idler wraps some other callable (a proc or object which responds to #call) The callable should return a falsy value when it did nothing, or a truthy value when it did something. The idler will sleep when there is nothing to do.
Defined Under Namespace
Modules: Utilities
Constant Summary collapse
- MIN_SLEEP =
0.125
- MAX_SLEEP =
1.0
Instance Attribute Summary collapse
-
#sleep ⇒ Object
readonly
Returns the value of attribute sleep.
Instance Method Summary collapse
- #call(*args, &block) ⇒ Object
- #call_with_wakefulness(callable, *args, &block) ⇒ Object
-
#initialize(callable = nil, options = {}, &callable_block) ⇒ Idler
constructor
A new instance of Idler.
- #sleep_more ⇒ Object
- #wake ⇒ Object
Methods included from Utilities
Constructor Details
#initialize(callable = nil, options = {}, &callable_block) ⇒ Idler
Returns a new instance of Idler.
19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/collective/idler.rb', line 19 def initialize( callable = nil, = {}, &callable_block ) @callable = callable || callable_block raise unless @callable.respond_to?(:call) @max_sleep = [:max_sleep] || MAX_SLEEP raise if @max_sleep <= 0 @min_sleep = [:min_sleep] || MIN_SLEEP raise if @min_sleep <= 0 raise if @max_sleep < @min_sleep @sleep = nil end |
Instance Attribute Details
#sleep ⇒ Object (readonly)
Returns the value of attribute sleep.
17 18 19 |
# File 'lib/collective/idler.rb', line 17 def sleep @sleep end |
Instance Method Details
#call(*args, &block) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/collective/idler.rb', line 33 def call( *args, &block ) result = call_with_wakefulness( @callable, *args, &block ) if result then wake else sleep_more end return result end |
#call_with_wakefulness(callable, *args, &block) ⇒ Object
46 47 48 49 50 51 52 53 |
# File 'lib/collective/idler.rb', line 46 def call_with_wakefulness( callable, *args, &block ) begin callable.call(*args,&block) rescue Exception # when errors occur, @sleep = @min_sleep # reduce sleeping almost all the way (but not to 0) raise # do not consume any exceptions end end |
#sleep_more ⇒ Object
55 56 57 58 59 60 61 62 |
# File 'lib/collective/idler.rb', line 55 def sleep_more if @sleep then @sleep = [ @sleep * 2, @max_sleep ].min else @sleep = @min_sleep end Kernel.sleep(@sleep) if @sleep # Interrupt will propogate through sleep(). end |
#wake ⇒ Object
64 65 66 |
# File 'lib/collective/idler.rb', line 64 def wake @sleep = nil end |