Created
May 1, 2009 02:58
-
-
Save pope/104837 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment