2012-04-09 5 views
1

RubyにJava ScheduledExecutorServiceのアナログがありますか?Java ScheduledExecutorServiceのRubyアナログ

代わりにこの:このような

Thread.new do 
    while true 
    puts "Do something..." 
    sleep 1 
    end 
end 

利用何か:

ScheduledExecutorService.new(timeout) do 
    puts "Do something..." 
end 

それは私が標準解決策を見つけることができませんでしたので、重要なものの

答えて

0

よりコンパクトかつ明確ではありませんが、あなたそれを実装するためにThreadを使用することができます:

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 
関連する問題