2012-12-20 29 views
2

我有一些任务执行很多操作,其中一些可以“阻止”,因为它调用外部API。Rails方法运行设置超时 - 确定线程在方法中“保留”的时间长度

我的问题:是否可以确定RailsThread在某个方法中“保留”多长时间?如果时间太长,则会中断或重新加载。问题是没有错误,所以我不能做任何事情,比如救援。

,我想做一个伪代码:

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

回答

7
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 
+0

谢谢你的好答案! – damoiser

相关问题