1

Does Ruby have analog of Java ScheduledExecutorService?

Instead this:

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

Use something like this:

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

It's not so critical but more compact and clearer

4

1 回答 1

0

我找不到标准解决方案,但您可以使用Threads 来实现它:

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
于 2012-04-09T17:42:46.513 回答