I want find a way to set a time limit on a ruby code so it will exits after that time limit has expired.
I'm not sure why this question is being downvoted, it is very simple to do with the timeout module.
This lets you pass a block and a time period. If the block completes within the time period, the value is returned. Otherwise an exception is thrown. Example use:
require 'timeout'
def run
begin
result = Timeout::timeout(2) do
sleep(1 + rand(3))
42
end
puts "The result was #{result}"
rescue Timeout::Error
puts "the calculation timed out"
end
end
In use:
2.0.0p0 :005 > load 'test.rb'
=> true
2.0.0p0 :006 > run
the calculation timed out
=> nil
2.0.0p0 :007 > run
the calculation timed out
=> nil
2.0.0p0 :008 > run
The result was 42
=> nil
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With