Class: Zold::Metronome

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

Overview

Metronome

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Metronome.



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

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

Instance Method Details

#add(routine) ⇒ Object



54
55
56
57
# File 'lib/zold/metronome.rb', line 54

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

#startObject



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/zold/metronome.rb', line 59

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).to_s
          @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



44
45
46
47
48
49
50
51
52
# File 'lib/zold/metronome.rb', line 44

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