views:

62

answers:

1

I want to run a task in Ruby for up to (say) 10 seconds, and kill that task if it has taken longer. This is to prevent hanging of an external process. What's the best way of implementing this? In particular, how would I write the function for_up_to_10_seconds below?

loop do
  for_up_to_10_seconds do
    # something
  end
end
+6  A: 

The Timeout class from the standard lib is what you're looking for: http://www.ruby-doc.org/core/classes/Timeout.html

loop do
  Timeout.timeout(10) do
    # something
  end
end
severin
I remember hearing that Timeout wasn't perfectly reliable, but I have no sources to back this up.
Trevoke
I only use threads a little bit, but I suspect that timeout doesn't rescue you from deadlock.
Andrew Grimm