Java ScheduledExecutorService的Ruby模拟

时间:2012-04-09 14:59:18

标签: ruby multithreading

Ruby是否具有Java ScheduledExecutorService的模拟?

取而代之的是:

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

使用类似的东西:

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

它不是那么重要,但更紧凑,更清晰

1 个答案:

答案 0 :(得分: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