Class: WDD::Utils::TimeGate
- Defined in:
- lib/wdd-ruby-ext/utils/time_gate.rb
Class Method Summary collapse
-
.elapsed_time(&block) ⇒ Object
Evaluated the passed block and returns the elapsed wall clock time.
-
.interruptable_sleep(sleep_time, guard_interval = 0.5) ⇒ Object
Sleeps the specified interval.
Instance Method Summary collapse
-
#initialize ⇒ TimeGate
constructor
A new instance of TimeGate.
- #set(seconds) ⇒ Object
-
#wait(block = true) ⇒ Object
Waits until the gate is opened.
Constructor Details
Class Method Details
.elapsed_time(&block) ⇒ Object
Evaluated the passed block and returns the elapsed wall clock time.
37 38 39 40 41 |
# File 'lib/wdd-ruby-ext/utils/time_gate.rb', line 37 def elapsed_time &block start_time = Time.now yield Time.now - start_time end |
.interruptable_sleep(sleep_time, guard_interval = 0.5) ⇒ Object
Sleeps the specified interval. If a block is passed, it will be evaluated every guard_interval
seconds. If it evaluates to true, the sleep will be interrupted and control will be returned to the caller.
45 46 47 48 49 50 51 52 53 54 |
# File 'lib/wdd-ruby-ext/utils/time_gate.rb', line 45 def interruptable_sleep sleep_time, guard_interval=0.5 if block_given? while( yield && sleep_time > 0 ) sleep guard_interval sleep_time -= guard_interval end else sleep sleep_time end end |
Instance Method Details
#set(seconds) ⇒ Object
11 12 13 |
# File 'lib/wdd-ruby-ext/utils/time_gate.rb', line 11 def set seconds @gate_time = Time.now + seconds end |
#wait(block = true) ⇒ Object
Waits until the gate is opened. block
- true by default. If false, the method will not block, but will return the amount of time left before the gate opens. An optional Ruby block can be passed when block
is true that will be evaluated every 0.5 seconds. If the block evaluates to false, the latch is released and this method returns.
20 21 22 23 24 25 26 27 28 29 |
# File 'lib/wdd-ruby-ext/utils/time_gate.rb', line 20 def wait block = true if block guard = block_given? ? yield : true while Time.now < @gate_time && guard do sleep 0.5 end else Time.now < @gate_time end end |