Ruby’s Timeout
If you think you’ve been around the block a few times and know your ins-and-outs of Ruby’s funkiest details, here’s a quick Ruby quiz for you: on MRI, what does this piece of code print out?
require 'timeout'
def do_stuff
sleep(2)
puts "done sleeping"
rescue => e
puts 'boom!'
ensure
puts 'all done'
end
begin
Timeout::timeout(1) do
do_stuff
end
rescue Timeout::Error
puts 'timed out'
end
If you answered timed out
, that’s not a bad start. After all, the timeout
method is what raises the error, right? Or… no, actually. Ruby’s timeout method actually works by kicking off a new thread, which sleeps for the timeout duration and then raises an exception on the original execution thread, at whatever point in the code it happens to be at. The stack trace will read as if it came from a random line in your code (which can be surprising to the uninitiated).
Okay, so it prints...