Class: Timeouter::Timer
- Inherits:
-
Object
- Object
- Timeouter::Timer
- Defined in:
- lib/timeouter/timer.rb
Instance Attribute Summary collapse
-
#started_at ⇒ Object
readonly
, :exhausted_at.
-
#timeout ⇒ Object
readonly
, :exhausted_at.
Instance Method Summary collapse
-
#elapsed ⇒ Object
elapsed time from creation.
-
#exhausted? ⇒ Boolean
is timeout exhausted? or nil when timeout was 0.
-
#initialize(timeout = 0, eclass: nil, message: nil) ⇒ Timer
constructor
A new instance of Timer.
-
#left ⇒ Object
time left to be exhausted or nil if timeout was 0.
-
#loop ⇒ Object
run block in loop until timeout reached.
- #loop!(eclass = @eclass, message: @message) ⇒ Object
-
#running!(eclass = @eclass, message: @message) ⇒ Object
ensure timeout NOT exhausted raise exception otherwise.
-
#running? ⇒ Boolean
is timeout NOT exhausted? or true when timeout was 0.
Constructor Details
#initialize(timeout = 0, eclass: nil, message: nil) ⇒ Timer
Returns a new instance of Timer.
8 9 10 11 12 13 14 15 16 17 |
# File 'lib/timeouter/timer.rb', line 8 def initialize(timeout = 0, eclass: nil, message: nil) # ensure only positive timeouts timeout ||= 0 @timeout = [timeout, 0].max @eclass = eclass || Timeouter::TimeoutError @message = || 'execution expired' @started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC) end |
Instance Attribute Details
#started_at ⇒ Object (readonly)
, :exhausted_at
6 7 8 |
# File 'lib/timeouter/timer.rb', line 6 def started_at @started_at end |
#timeout ⇒ Object (readonly)
, :exhausted_at
6 7 8 |
# File 'lib/timeouter/timer.rb', line 6 def timeout @timeout end |
Instance Method Details
#elapsed ⇒ Object
elapsed time from creation
20 21 22 |
# File 'lib/timeouter/timer.rb', line 20 def elapsed Process.clock_gettime(Process::CLOCK_MONOTONIC) - @started_at end |
#exhausted? ⇒ Boolean
is timeout exhausted? or nil when timeout was 0
30 31 32 |
# File 'lib/timeouter/timer.rb', line 30 def exhausted? (@timeout > 0) ? elapsed > @timeout : nil end |
#left ⇒ Object
time left to be exhausted or nil if timeout was 0
25 26 27 |
# File 'lib/timeouter/timer.rb', line 25 def left (@timeout > 0) ? [@timeout - elapsed, 0].max : nil end |
#loop ⇒ Object
run block in loop until timeout reached. Use break for returning result
45 46 47 |
# File 'lib/timeouter/timer.rb', line 45 def loop yield(self) while self.running? end |
#loop!(eclass = @eclass, message: @message) ⇒ Object
49 50 51 |
# File 'lib/timeouter/timer.rb', line 49 def loop!(eclass = @eclass, message: @message) yield(self) while self.running!(eclass, message: ) end |
#running!(eclass = @eclass, message: @message) ⇒ Object
ensure timeout NOT exhausted raise exception otherwise
40 41 42 |
# File 'lib/timeouter/timer.rb', line 40 def running!(eclass = @eclass, message: @message) !exhausted? || (raise eclass.new()) end |
#running? ⇒ Boolean
is timeout NOT exhausted? or true when timeout was 0
35 36 37 |
# File 'lib/timeouter/timer.rb', line 35 def running? !exhausted? end |