On 5/27/09, Anonymous <derykus / gmail.com> wrote:
> I'm totally new to Ruby so I'm sorry for the  piggyback question but,
> in Perl you could
> set an alarm clock that'd leave the program unfettered:
>
>
>   { local $SIG{ALRM} = sub { die "timeout" };
>     alarm( "target_time" - "Time.now" );
>      # do other things
>     alarm( 0 );
>   };
>   if ( $@ =~ /^timeout/ ) {# time's up... }
>   elsif ( $@ )            {# other error... }
>
>
> How would Ruby do this?

I went and looked again, and there is a Timeout module in ruby's
stdlib, which I had forgotten about:
http://www.ruby-doc.org/stdlib/libdoc/timeout/rdoc/index.html

So the equivalent of the perl code you posted should be:

#UNTESTED!!!
require 'timeout'
begin
  Timeout.timeout(target_time-Time.now){
    #do other things
  }
rescue Timeout::Error
  #time's up
rescue Exception
  #other error
end

Timeout uses Thread#raise, which I think is not reliable on JRuby or
other implementations that use native threads.

PS: does anyone know why Timeout::Error < Interrupt ? Interrupt is for
^C... why would you want timeouts to be handled like ^C?