title: Is there a way to write a Ruby loop that runs one iteration for a maximum set amount of time?
body: <p>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.</p>
  
  <p>For example, this is what I'm hoping to achieve:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>So far, I've found tarcieri's gem called Timers (<a href="https://github.com/tarcieri/timers" rel="nofollow">https://github.com/tarcieri/timers</a>) 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?</p>