Class: Workers::Timer

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

Direct Known Subclasses

PeriodicTimer

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(delay, options = {}, &block) ⇒ Timer

Returns a new instance of Timer.



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

def initialize(delay, options = {}, &block)
  @delay = delay
  @callback = options[:callback] || block
  @repeat = options[:repeat] || false
  @scheduler = options[:scheduler] || Workers.scheduler
  @logger = options[:logger]

  @mutex = Mutex.new

  reset

  @scheduler.schedule(self)
end

Instance Attribute Details

#delayObject (readonly)

Returns the value of attribute delay.



3
4
5
# File 'lib/workers/timer.rb', line 3

def delay
  @delay
end

#repeatObject (readonly)

Returns the value of attribute repeat.



4
5
6
# File 'lib/workers/timer.rb', line 4

def repeat
  @repeat
end

Instance Method Details

#<=>(other) ⇒ Object



20
21
22
# File 'lib/workers/timer.rb', line 20

def <=>(other)
  return sec_remaining <=> other.sec_remaining
end

#cancelObject



44
45
46
47
48
# File 'lib/workers/timer.rb', line 44

def cancel
  @scheduler.unschedule(self)

  return nil
end

#fireObject



36
37
38
39
40
41
42
# File 'lib/workers/timer.rb', line 36

def fire
  @mutex.synchronize do
    @callback.call if @callback
  end

  return nil
end

#overdue?Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/workers/timer.rb', line 32

def overdue?
    return sec_remaining <= 0
end

#resetObject



50
51
52
53
54
55
56
# File 'lib/workers/timer.rb', line 50

def reset
  @mutex.synchronize do
    @fire_at = Time.now.utc + @delay
  end

  return nil
end

#sec_remainingObject



24
25
26
27
28
29
30
# File 'lib/workers/timer.rb', line 24

def sec_remaining
  @mutex.synchronize do
    diff = @fire_at.to_f - Time.now.utc.to_f

    return (diff > 0) ? diff : 0
  end
end