有没有办法编写一个Ruby循环,在最长设定的时间内运行一次迭代?

Han*_*Han 1 ruby loops timer

我正在寻找创建一个Ruby(MRI 1.9.3)循环,该循环最多运行一段时间,并且一旦该时间结束,它将进入循环的下一次迭代.

例如,这是我希望实现的目标:

timer = Timer.new
while foo
  timer.after 5 do # The loop on foo only gets to run for 5 seconds
    next
  end

  # Do some work here
end
Run Code Online (Sandbox Code Playgroud)

到目前为止,我发现tarcieri的gem叫做Timers(https://github.com/tarcieri/timers),这是我在上面的代码中试图模仿的,但是我的实现没有给出我期望的行为,如果我的工作需要更长的时间,那么循环在5秒后进入下一次迭代.有任何想法吗?

Ere*_*bih 10

require 'timeout'
timeout_in_seconds = 5
while foo
  begin
    Timeout.timeout(timeout_in_seconds) do
      # Do some work here
    end
  rescue Timeout::Error
    next
  end
end
Run Code Online (Sandbox Code Playgroud)