Han Han - 5 months ago 24
Ruby Question

Is there a way to write a Ruby loop that runs one iteration for a maximum set amount of time?

I'm looking to create a Ruby (MRI 1.9.3) loop that runs at most for a certain amount of time, and once that time is up it goes to the next iteration of the loop.

For example, this is what I'm hoping to achieve:

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


So far, I've found tarcieri's gem called Timers (https://github.com/tarcieri/timers) which is what I'm trying to emulate in the code above, but my implementation doesn't give the behavior I expect, which is for the loop to go to the next iteration after 5 seconds if my work takes longer than that. Any ideas?

Answer
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
Comments