Class: Promiscuous::Timer

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

Instance Method Summary collapse

Constructor Details

#initialize(name, duration, &block) ⇒ Timer

Returns a new instance of Timer.



2
3
4
5
6
7
# File 'lib/promiscuous/timer.rb', line 2

def initialize(name, duration, &block)
  @name = name
  @duration = duration.to_f
  @block = block
  @lock = Mutex.new
end

Instance Method Details

#main_loop(options = {}) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/promiscuous/timer.rb', line 20

def main_loop(options={})
  Thread.current[:promiscuous_timer_instance] = self
  options = options.dup

  loop do
    sleep @duration unless options.delete(:run_immediately)
    @lock.synchronize do
      return unless @thread
      run_callback
    end
  end
end

#resetObject



39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/promiscuous/timer.rb', line 39

def reset
  if Thread.current[:promiscuous_timer_instance] == self
    # We already hold the lock (the callback called reset)
    @thread = nil
  else
    @lock.synchronize do
      @thread.try(:kill)
      @thread = nil
    end
  end
  @last_exception = nil
end

#run_callbackObject



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

def run_callback
  @block.call
rescue Exception => e
  # Report the exception only once
  unless @last_exception == e.to_s
    @last_exception = e.to_s
    Promiscuous.warn "[#{@name}] #{e}"
    Promiscuous::Config.error_notifier.call(e)
  end
end

#start(options = {}) ⇒ Object



33
34
35
36
37
# File 'lib/promiscuous/timer.rb', line 33

def start(options={})
  @lock.synchronize do
    @thread ||= Thread.new { main_loop(options) }
  end
end