Ruby Timeout :: timeout no activa la excepción y no devuelve lo documentado

Tengo este fragmento de código:

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.

¿Estoy haciendo algo mal?

preguntado el 09 de enero de 11 a las 02:01

3 Respuestas

Tu código es correcto

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.

Respondido el 09 de enero de 11 a las 05:01

You were definitively right. I Don't know why i didn't check platform.search. Actually, search was rescueing.. Exception... Thank's a lot! - Pasta

El problema es que 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 

contestado el 14 de mayo de 12 a las 17:05

I recently described and, possibly, fixed this problem, here: code.jjb.cc/2012/09/15/… - John Bachir

Timeout does suck, but this Threaded approach works well, thanks - Matthew O'Riordan

Según la documentación:

If the block execution terminates before sec seconds has passed, it returns true. If not, it terminates the execution and raises exception (which defaults to Timeout::Error)

This means it only returns true if it's successful, otherwise the variable will not be set (ie it's nil NOT false).

As far as your example goes, it's definitely timing out for me and getting to the rescue part...

Respondido el 09 de enero de 11 a las 05:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.