如何设置运行Ruby代码的时间限制

Jus*_*est 12 ruby

我想找到一种方法来设置ruby代码的时间限制,以便在该时间限制到期后退出.

Dav*_*ani 21

我不确定为什么这个问题被downvoted,使用超时模块非常简单.

这使您可以传递一个块和一个时间段.如果块在该时间段内完成,则返回该值.否则抛出异常.使用示例:

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
Run Code Online (Sandbox Code Playgroud)

正在使用:

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
Run Code Online (Sandbox Code Playgroud)