Class: Timeouter::Timer

Inherits:
Object
  • Object
show all
Defined in:
lib/timeouter/timer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

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 = message || 'execution expired'

  @started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
end

Instance Attribute Details

#started_atObject (readonly)

, :exhausted_at



6
7
8
# File 'lib/timeouter/timer.rb', line 6

def started_at
  @started_at
end

#timeoutObject (readonly)

, :exhausted_at



6
7
8
# File 'lib/timeouter/timer.rb', line 6

def timeout
  @timeout
end

Instance Method Details

#elapsedObject

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

Returns:

  • (Boolean)


30
31
32
# File 'lib/timeouter/timer.rb', line 30

def exhausted?
  (@timeout > 0) ? elapsed > @timeout : nil
end

#leftObject

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

#loopObject

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: 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(message))
end

#running?Boolean

is timeout NOT exhausted? or true when timeout was 0

Returns:

  • (Boolean)


35
36
37
# File 'lib/timeouter/timer.rb', line 35

def running?
  !exhausted?
end