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: Timeouter::TimeoutError, emessage: 'execution expired') ⇒ Timer

Returns a new instance of Timer.



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/timeouter/timer.rb', line 8

def initialize(timeout = 0, eclass: Timeouter::TimeoutError, emessage: 'execution expired')
  # ensure only positive timeouts
  timeout ||= 0
  timeout = [timeout, 0].max

  @eclass = eclass
  @emessage = emessage

  @started_at = Time.now
  @exhausted_at = timeout > 0 ? @started_at + timeout : nil
end

Instance Attribute Details

#exhausted_atObject (readonly)

Returns the value of attribute exhausted_at.



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

def exhausted_at
  @exhausted_at
end

#started_atObject (readonly)

Returns the value of attribute started_at.



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

def started_at
  @started_at
end

Instance Method Details

#elapsedObject

elapsed time from creation



21
22
23
# File 'lib/timeouter/timer.rb', line 21

def elapsed
  Time.now - @started_at
end

#exhausted?Boolean

is timeout exhausted? or nil when timeout was 0

Returns:

  • (Boolean)


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

def exhausted?
  @exhausted_at && (@exhausted_at < Time.now)
end

#leftObject

time left to be exhausted or nil if timeout was 0



26
27
28
# File 'lib/timeouter/timer.rb', line 26

def left
  @exhausted_at && [@exhausted_at - Time.now, 0].max
end

#loopObject

run block in loop until timeout reached. Use break for returning result



46
47
48
# File 'lib/timeouter/timer.rb', line 46

def loop
  yield(self) while self.running?
end

#loop!(eclass = @eclass, message: @emessage) ⇒ Object



50
51
52
# File 'lib/timeouter/timer.rb', line 50

def loop!(eclass = @eclass, message: @emessage)
  yield(self) while self.running!(eclass, message: message)
end

#running!(eclass = @eclass, message: @emessage) ⇒ Object

ensure timeout NOT exhausted raise exception otherwise



41
42
43
# File 'lib/timeouter/timer.rb', line 41

def running!(eclass = @eclass, message: @emessage)
  !exhausted? || (raise eclass.new(message))
end

#running?Boolean

is timeout NOT exhausted? or true when timeout was 0

Returns:

  • (Boolean)


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

def running?
  !exhausted?
end