How to set a time limit for running Ruby code

I want to find a way to set a time limit on ruby ​​code so that it exits after this period expires.

+8
ruby
source share
1 answer

I am not sure why this question is ignored, it is very simple to do with the timeout module.

This allows you to transfer a block and a period of time. If the block completes within a period of time, a value is returned. Otherwise, an exception is thrown. Usage example:

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 

Using:

 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 
+15
source share

All Articles