Class: Snmp2mkr::EngineThreads::Timer

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

Defined Under Namespace

Classes: Entry

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger: Logger.new($stdout)) ⇒ Timer

Returns a new instance of Timer.



6
7
8
9
10
11
# File 'lib/snmp2mkr/engine_threads/timer.rb', line 6

def initialize(logger: Logger.new($stdout))
  @shutdown = false
  @entries = []
  @logger = logger
  @thread = nil
end

Instance Attribute Details

#entriesObject (readonly)

Returns the value of attribute entries.



13
14
15
# File 'lib/snmp2mkr/engine_threads/timer.rb', line 13

def entries
  @entries
end

#loggerObject (readonly)

Returns the value of attribute logger.



13
14
15
# File 'lib/snmp2mkr/engine_threads/timer.rb', line 13

def logger
  @logger
end

#threadObject (readonly)

Returns the value of attribute thread.



13
14
15
# File 'lib/snmp2mkr/engine_threads/timer.rb', line 13

def thread
  @thread
end

Instance Method Details

#add(interval, &hook) ⇒ Object



15
16
17
18
19
# File 'lib/snmp2mkr/engine_threads/timer.rb', line 15

def add(interval, &hook)
  entry = Entry.new(interval, hook, now - interval + rand(15))
  logger.info "Added timer #{entry.inspect}"
  @entries << entry
end

#joinObject



25
26
27
28
# File 'lib/snmp2mkr/engine_threads/timer.rb', line 25

def join
  return unless running?
  @thread.join
end

#kick(entry) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
# File 'lib/snmp2mkr/engine_threads/timer.rb', line 61

def kick(entry)
  logger.debug "timer kick entry #{entry.inspect}"
  entry.last = now
  Thread.new do
    begin
      entry.hook.call
    rescue Exception => e
      logger.error "#{e.inspect}\n\t#{e.backtrace.join("\n\t")}"
    end
  end
end

#main_loopObject



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/snmp2mkr/engine_threads/timer.rb', line 41

def main_loop
  logger.info "timer started"
  loop do
    break if @shutdown
    tick
    sleep 1
  end
  logger.info "timer shutdown"
rescue Exception => e
  logger.error "#{e.inspect}\n\t#{e.backtrace.join("\n\t")}"
  retry
end

#running?Boolean

Returns:

  • (Boolean)


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

def running?
  @thread && @thread.alive?
end

#startObject



30
31
32
33
34
# File 'lib/snmp2mkr/engine_threads/timer.rb', line 30

def start
  return if running?
  @shutdown = false
  @thread = Thread.new(&method(:main_loop))
end

#stopObject



36
37
38
39
# File 'lib/snmp2mkr/engine_threads/timer.rb', line 36

def stop
  return unless running?
  @shutdown = true
end

#tickObject



54
55
56
57
58
59
# File 'lib/snmp2mkr/engine_threads/timer.rb', line 54

def tick
  t = now
  @entries.each do |entry|
    kick(entry) if (now - entry.last) > entry.interval
  end
end