1

我可以使用此代码为我的函数引入超时

require 'timeout'
Timeout::timeout(timeout_period) do
  run_some_code
rescue => err
  do_something_with err
  # and maybe the below?
  raise
end

我怎样才能创建另一个my_timeout我可以重复使用的功能?我希望能够指定在超时“需要”再次运行的情况下调用的函数。

那么我会打电话my_timeoutmy_timeout('function name',int_how_many_times_to repeat_if times_out)

  • my_timeout("restart_db2_server",5)
  • my_timeout("restart_eduserver",3)
  • my_timeout("run_test",0)

ruby 1.9.3p194 (2012-04-20) [i386-mingw32]在Windows7上使用

4

1 回答 1

1
def my_timeout repeat_n_times, timeout_period, &block
  Timeout::timeout timeout_period, &block
rescue Timeout::Error => timeout_error
  repeat_n_times -= 1

  if repeat_n_times > 0
    retry
  else
    raise timeout_error
  end
end

# Example

# execute the block with a timeout of 30 and repeat up to 5 times
my_timeout 5, 30 do
  # do the heavy work
end
于 2012-10-04T23:24:34.593 回答