Timeouter is advisory timeout helper without any background threads.
Typical usage scenario:
require'timeouter'Timeouter::run(3)do |t|
sleep1# do some workputst.elapsed# 1.00011811putst.left# 1.99985717 or nil if timeout was 0putst.exhausted?# false or nil if timeout was 0putst.running?# trueputst.running!# truesleep3# do another workputst.elapsed# 4.000177464putst.left# 0 or nil if timeout was 0putst.exhausted?# true or nil if timeout was 0putst.running?# falseputst.running!# raise Timeouter::TimeoutError.new('execution expired')endYou can pass exception class and message on creation or on checking:
Timeouter::run(1,eclass: RuntimeError,message: 'error')do |t|
sleep2putst.running!(eclass: MyError,message: 'myerror')endLoop helper:
# just loop 3 secondsTimeouter::loop(3)do |t|
puts"i'am in loop"sleep1end# just loop 3 seconds and raise exception thenTimeouter::loop!(3,eclass: MyError)do |t|
puts"i'am in loop and not raised yet"sleep1end# Break the loop after some success and retuel valueresult=Timeouter::loop!(3)do |t|
puts"i'am in loop and not raised yet"ift.elapsed > 1puts"work done breaking loop"break"RESULT"endsleep1endIt's a gem:
gem install timeouterThere's also the wonders of the Gemfile:
gem'timeouter'