Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Timeout::timeout doesn't fire Exception and doesn't return what documented

I have this piece of code:

begin
  complete_results = Timeout.timeout(4) do      
    results = platform.search(artist, album_name)
  end
rescue Timeout::Error
  puts 'Print me something please'
end 

I then launch the method containing this code, and well, here is the beginning of a stack trace:

Exception message :  execution expired
Exception backtrace :  /***/****/.rvm/rubies/ruby-1.8.7-p302/lib/ruby/1.8/timeout.rb:64:i

So I naively thinks that my call timed out, but 'Print me something please' is never printed and complete_results which is suppose to be the timeout status return value (either true or false, as mentioned in the documentation), is definitively not a boolean.

Am I doing something wrong?

like image 709
Pasta Avatar asked Jan 09 '11 02:01

Pasta


2 Answers

Your code is correct

require 'timeout'
begin
  complete_results = Timeout.timeout(1) do      
   sleep(2)
  end
rescue Timeout::Error
  puts 'Print me something please'
end

does print out "print me something please".

Try the basic code as above. If that works, you have an issue in platform.search.

like image 157
David Sulc Avatar answered Oct 08 '22 21:10

David Sulc


The problem is that platform.search is catching the exception that Timeout#timeout throws.

You can get around this by wrapping your inner code in another thread -- YMMV.

begin
  complete_results = Timeout.timeout(4) do
    Thread.new{ results = platform.search(artist, album_name) }.value
  end
rescue Timeout::Error
  puts 'Print me something please'
end 
like image 37
John Bachir Avatar answered Oct 08 '22 21:10

John Bachir