pope (owner)

Forks

Revisions

gist: 104837 Download_button fork
public
Public Clone URL: git://gist.github.com/104837.git
Embed All Files: show embed
periodic_reactor.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
require 'time'
 
class PeriodicExecutor
 
  attr_reader :next_time_to_run
 
  def initialize(secs, &block)
    @secs = secs
    @block = block
    @next_time_to_run = Time.now.to_f
  end
 
  def call()
    @next_time_to_run = Time.now.to_f + @secs
    @block.call()
  end
 
  def <=>(other)
    @next_time_to_run <=> other.next_time_to_run
  end
end
 
class PeriodicReactor
 
  def initialize()
    @executors = []
  end
 
  def add_periodic_executor(secs, &block)
    @executors << PeriodicExecutor.new(secs, &block)
    @executors.sort!
  end
 
  def run()
    while true and @executors.size != 0
      while Time.now.to_f >= @executors.first.next_time_to_run
        @executors.first.call()
        @executors.sort!
      end
      sleep(@executors.first.next_time_to_run - Time.now.to_f)
    end
  end
end
 
if __FILE__ == $0
  r = PeriodicReactor.new
  r.add_periodic_executor(3) do
    puts "A"
  end
  r.add_periodic_executor(5) do
    puts "B"
  end
  r.run()
end