標準ソリューションが見つかりませんでしたが、Thread
sを使用して実装できます。
class ScheduledExecutor
def threads
@threads ||= []
end
def initialize(options = {}, &block)
schedule options, &block unless block.nil?
end
def schedule(options = {}, &block)
period = options.fetch :period, nil
delay = options.fetch :delay, 0
threads << Thread.new do
sleep delay
begin
block.call
end while period and sleep period
end
end
end
# Will it work?
puts Time.now; ScheduledExecutor.new(delay: 1, period: 2) { puts Time.now }
2012-04-09 14:46:57 -0300
2012-04-09 14:46:58 -0300
2012-04-09 14:47:00 -0300
2012-04-09 14:47:02 -0300
2012-04-09 14:47:04 -0300
2012-04-09 14:47:06 -0300
2012-04-09 14:47:08 -0300
2012-04-09 14:47:10 -0300