我对Ruby还是个新手,我第一次尝试将Timeout用于一些HTTP函数,但很明显我在某个地方没有注意到这一点。我的代码在下面,但它不起作用。相反,它引发了以下异常:
C:/Ruby193/lib/ruby/1.9.1/net/http.rb:762:in `initialize': execution expired (Timeout::Error)
这对我来说没有多大意义,因为它超时的代码部分被包裹在一个开始/救援/结束块中,特别是救援Timeout::Error。我是做错了什么,还是Ruby不支持的事情?
retries = 10
Timeout::timeout(5) do
begin
File.open("#{$temp}\http.log", 'w') { |f|
http.request(request) do |str|
f.write str.body
end
}
rescue Timeout::Error
if retries > 0
print "Timeout - Retrying..."
retries -= 1
retry
else
puts "ERROR: Not responding after 10 retries! Giving up!")
exit
end
end
end
Timeout::Error
在对Timeout::timeout
的调用中被引发,因此您需要将其放入begin
块中:
retries = 10
begin
Timeout::timeout(5) do
File.open("#{$temp}\http.log", 'w') do |f|
http.request(request) do |str|
f.write str.body
end
end
end
rescue Timeout::Error
if retries > 0
print "Timeout - Retrying..."
retries -= 1
retry
else
puts "ERROR: Not responding after 10 retries! Giving up!")
exit
end
end
使用retryable使这个简单的
https://github.com/nfedyashev/retryable#readme
require "open-uri"
retryable(:tries => 3, :on => OpenURI::HTTPError) do
xml = open("http://example.com/test.xml").read
end