Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a time limit for a Ruby code to run

Tags:

ruby

I want find a way to set a time limit on a ruby code so it will exits after that time limit has expired.

like image 966
JustForTest Avatar asked May 09 '13 04:05

JustForTest


1 Answers

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
like image 187
David Miani Avatar answered Sep 21 '22 09:09

David Miani