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::Quiet.new) ⇒ Metronome

Returns a new instance of Metronome.


32
33
34
35
36
37
# File 'lib/zold/metronome.rb', line 32

def initialize(log = Log::Quiet.new)
  @log = log
  @routines = []
  @threads = []
  @failures = {}
end

Instance Method Details

#add(routine) ⇒ Object


45
46
47
48
# File 'lib/zold/metronome.rb', line 45

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

#startObject


50
51
52
53
54
55
56
57
58
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
86
87
# File 'lib/zold/metronome.rb', line 50

def start
  alive = true
  @routines.each do |r|
    @threads << Thread.start do
      Thread.current.name = r.class.name
      step = 0
      while alive
        start = Time.now
        begin
          r.exec(step)
        rescue StandardError => e
          @failures[r.class.name] = Backtrace.new(e).to_s
        end
        step += 1
        @log.info("Routine #{r.class.name} ##{step} done in #{(Time.now - start).round(2)}s: \
#{@threads.map { |t| "#{t.name}/#{t.status}" }.join(',')}")
        sleep(1)
      end
    end
  end
  begin
    yield(self)
  ensure
    alive = false
    @log.info("Stopping the metronome with #{@threads.count} threads: #{@threads.map(&:name).join(', ')}")
    start = Time.now
    @threads.each do |t|
      tstart = Time.now
      if t.join(60)
        @log.info("Thread #{t.name} finished in #{(Time.now - tstart).round(2)}s")
      else
        t.exit
        @log.info("Thread #{t.name} killed in #{(Time.now - tstart).round(2)}s")
      end
    end
    @log.info("Metronome stopped in #{(Time.now - start).round(2)}s, #{@failures.count} failures")
  end
end

#to_textObject


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

def to_text
  @threads.map do |t|
    "#{t.name}: status=#{t.status}; alive=#{t.alive?};\n  #{t.backtrace.join("\n  ")}"
  end.join("\n") + "\n\n" + @failures.map { |r, f| "#{r}\n#{f}\n" }.join("\n")
end