Class: Workers::Timer

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

Direct Known Subclasses

PeriodicTimer

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helpers

#concat_e, #log_debug, #log_error, #log_info, #log_warn

Constructor Details

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

Returns a new instance of Timer.



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

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

  reset
  @scheduler.schedule(self)

  return nil
end

Instance Attribute Details

#delayObject (readonly)

Returns the value of attribute delay.



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

def delay
  @delay
end

#repeatObject (readonly)

Returns the value of attribute repeat.



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

def repeat
  @repeat
end

Instance Method Details

#<=>(other) ⇒ Object



22
23
24
# File 'lib/workers/timer.rb', line 22

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

#cancelObject



46
47
48
49
50
# File 'lib/workers/timer.rb', line 46

def cancel
  @scheduler.unschedule(self)

  return nil
end

#fireObject



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

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

  return nil
end

#overdue?Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/workers/timer.rb', line 34

def overdue?
    return sec_remaining <= 0
end

#resetObject



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

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

  return nil
end

#sec_remainingObject



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

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

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