3

我有一个任务可以做很多事情,其中​​一些可能会“阻塞”,因为它调用了外部 API。

我的问题:是否可以确定 RailsThread 在方法中“停留”多长时间?依此类推,如果花费太长时间,则会中断它或重新加载。问题是没有错误,所以我不能做救援之类的事情。

我想做的伪代码:

def aMethod
  #doSomethingThatCanBlock
  if takeMoreThan1000ms
    #reloadMethod or break
  end
end
4

1 回答 1

8
require 'timeout'

def a_method(iterations)
  Timeout::timeout(1) do # 1 second
    iterations.times { |i| print("#{i} "); sleep(0.1) }
  end
rescue Timeout::Error
  print("TIMEOUT")
ensure
  puts
end

还有一个例子:

irb(main):012:0> a_method(3)
0 1 2 
=> 3
irb(main):013:0> a_method(30)
0 1 2 3 4 5 6 7 8 9 TIMEOUT
=> nil
于 2012-12-20T15:30:32.870 回答