Class: BigBen

Inherits:
Object
  • Object
show all
Defined in:
lib/bigben.rb,
lib/bigben/version.rb

Constant Summary collapse

VERSION =
'0.0.1'

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of BigBen.



7
8
9
10
11
12
# File 'lib/bigben.rb', line 7

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

Instance Method Details

#main_loop(options = {}) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/bigben.rb', line 26

def main_loop(options={})
  Thread.current[:bigben_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



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/bigben.rb', line 45

def reset
  if Thread.current[:bigben_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



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/bigben.rb', line 14

def run_callback
  @block.call
rescue Exception => e
  # Report the exception only once
  unless @last_exception == e.to_s
    @last_exception = e.to_s

    self.logger.warn "[#{@name}] #{e}" if self.logger
    self.notifier.call(e)              if self.notifier
  end
end

#start(options = {}) ⇒ Object



39
40
41
42
43
# File 'lib/bigben.rb', line 39

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