require'timeout'begincomplete_results=Timeout.timeout(1)dosleep(2)endrescueTimeout::Errorputs'Print me something please'end
sometime, the code inner with begin will catch exception
such as:
1234567891011121314151617
require'timeout'puts"#{Time.now}: Starting"beginTimeout.timeout(5)dobeginsleep10rescueException=>eputs"#{Time.now}: Caught an exception: #{e.inspect}"endsleep10endrescueTimeout::Error=>eputs"#{Time.now}: Timeout: #{e}"elseputs"#{Time.now}: Never timed out."end
so new a thread, as ruby 1.9 thread is native
1234567
begincomplete_results=Timeout.timeout(4)doThread.new{results=platform.search(artist,album_name)}.valueendrescueTimeout::Errorputs'Print me something please'end
implementation
1234567891011121314151617
# From lib/timeout.rbdeftimeout(sec,exception=Error)returnyieldifsec==nilorsec.zero?raiseThreadError,"timeout within critical session"ifThread.criticalbeginx=Thread.currenty=Thread.start{sleepsecx.raiseexception,"execution expired"ifx.alive?}yieldsec# return trueensurey.killifyandy.alive?endend