Class: Zold::Metronome

Inherits:
Object
  • Object
show all
Defined in:
lib/zold/metronome.rb

Overview

Metronome

Instance Method Summary collapse

Constructor Details

#initialize(log = Loog::NULL) ⇒ Metronome

Returns a new instance of Metronome.



20
21
22
23
24
25
# File 'lib/zold/metronome.rb', line 20

def initialize(log = Loog::NULL)
  @log = log
  @routines = []
  @threads = ThreadPool.new('metronome', log: log)
  @failures = {}
end

Instance Method Details

#add(routine) ⇒ Object



37
38
39
40
# File 'lib/zold/metronome.rb', line 37

def add(routine)
  @routines << routine
  @log.info("Added #{routine.class.name} to the metronome")
end

#startObject



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/zold/metronome.rb', line 42

def start
  @routines.each_with_index do |r, idx|
    @threads.add do
      step = 0
      Endless.new("#{r.class.name}-#{idx}", log: @log).run do
        Thread.current.thread_variable_set(:start, Time.now)
        step += 1
        begin
          r.exec(step)
          @log.debug("Routine #{r.class.name} ##{step} done \
in #{Age.new(Thread.current.thread_variable_get(:start))}")
        rescue StandardError => e
          @failures[r.class.name] = "#{Time.now.utc.iso8601}\n#{Backtrace.new(e)}"
          @log.error("Routine #{r.class.name} ##{step} failed \
in #{Age.new(Thread.current.thread_variable_get(:start))}")
          raise e
        end
        sleep(1)
      end
    end
  end
  begin
    yield(self)
  ensure
    @threads.kill
  end
end

#to_textObject



27
28
29
30
31
32
33
34
35
# File 'lib/zold/metronome.rb', line 27

def to_text
  [
    Time.now.utc.iso8601,
    'Current threads:',
    @threads.to_s,
    'Failures:',
    @failures.map { |r, f| "#{r}\n#{f}\n" }
  ].flatten.join("\n\n")
end