2014-09-26 44 views
1

我想查看下面代碼中使用Benchmark訪問URL所花費的時間。我也試圖在沒有基準的情況下做同樣的事情。也就是說,在測試開始和測試結束時獲得時間,減去兩者以獲得時間。兩種方法都以相同的超時錯誤結束。防止連接到URL時發生超時

require 'open-uri' 
require 'benchmark' 

response = nil 
puts "opening website with benchmark..." 
puts Benchmark.measure{ 
    response = open('http://mywebsite.com') 
} 

puts "Done !" 
status = response.status 
puts status 

錯誤:

opening website with benchmark... 
C:/ruby/lib/ruby/1.8/timeout.rb:64:in `rbuf_fill': execution expired (Timeout::Error) 
    from C:/ruby/lib/ruby/1.8/net/protocol.rb:134:in `rbuf_fill' 
    from C:/ruby/lib/ruby/1.8/net/protocol.rb:116:in `readuntil' 
    from C:/ruby/lib/ruby/1.8/net/protocol.rb:126:in `readline' 
    from C:/ruby/lib/ruby/1.8/net/http.rb:2028:in `read_status_line' 
    from C:/ruby/lib/ruby/1.8/net/http.rb:2017:in `read_new' 
    from C:/ruby/lib/ruby/1.8/net/http.rb:1051:in `request' 
    from C:/ruby/lib/ruby/1.8/open-uri.rb:248:in `open_http' 
    from C:/ruby/lib/ruby/1.8/net/http.rb:543:in `start' 
    from C:/ruby/lib/ruby/1.8/open-uri.rb:242:in `open_http' 
    from C:/ruby/lib/ruby/1.8/open-uri.rb:616:in `buffer_open' 
    from C:/ruby/lib/ruby/1.8/open-uri.rb:164:in `open_loop' 
    from C:/ruby/lib/ruby/1.8/open-uri.rb:162:in `catch' 
    from C:/ruby/lib/ruby/1.8/open-uri.rb:162:in `open_loop' 
    from C:/ruby/lib/ruby/1.8/open-uri.rb:132:in `open_uri' 
    from C:/ruby/lib/ruby/1.8/open-uri.rb:518:in `open' 
    from C:/ruby/lib/ruby/1.8/open-uri.rb:30:in `open' 
    from C:/code/test.rb:7 
    from C:/ruby/lib/ruby/1.8/benchmark.rb:293:in `measure' 
    from C:/code/test.rb:6 

當我嘗試連接到這個網址在瀏覽器中,大約需要2-3分鐘訪問,所有的時間。

我搜索谷歌,但沒有找到有用的答案,我的問題。我知道我必須 更改超時設置的東西,但無法弄清楚哪一個。有人可以幫忙嗎?

回答

9

使用:read_timeout選項,以秒爲單位,例如,

open('foo.com', :read_timeout => 10) 

http://ruby-doc.org/stdlib-1.8.7/libdoc/open-uri/rdoc/OpenURI/OpenRead.html

+0

謝謝。如何將超時設置爲無窮大?無法從您提供的鏈接中快速獲得答案。超時= -1 – 2014-09-26 19:32:56

+0

我得到的錯誤 - '語法錯誤,意外':',期待')' response = open(url,read_timeout:300)' – 2014-09-26 19:33:48

+0

@BoratSagdiyev ...您應該使用正確的映射語法爲您的Ruby版本然後。我會編輯我的答案,但能夠從代碼示例中推斷出來是一項寶貴的技能。 – 2014-09-26 19:43:34

0

您可以隨時在Timeout把這個包:

Timeout.timeout(5) do 
    response = open('http://mywebsite.com') 
end 

,這將拋出一個異常Timeout::Error你需要捕捉。

+0

使用此方法有什麼缺點嗎?謝謝。 – 2014-09-26 20:40:02

+0

'open'已經在60秒內引發了一個'超時'。 – Matt 2014-09-27 09:26:26

+0

使用超時庫可能會有後果 - http://www.mikeperham.com/2015/05/08/timeout-rubys-most-dangerous-api/。 – plainjimbo 2016-03-11 01:09:31

2

的​​類Net::HTTP將使用該open-uri然後使用該請求具有read_timeout attribute set to 60 seconds的連接。

Net::HTTP類提供setter read_timeout for that

不幸的是,open-urisets up這種請求的方式並不能爲您提供在請求之前獲取該設置的方法,或輕鬆覆蓋默認值60

您可能需要自己使用Net::HTTP

link = URI.parse(url) 
request = Net::HTTP::Get.new(link.path) 
response = Net::HTTP.start(link.host, link.port) {|http| 
    http.read_timeout = 100 #Default is 60 seconds 
    http.request(request) 
} 

代碼從this answer

編輯被盜:或升級到1.9,它支持的:read_timeout = x選項戴夫牛頓說。

+0

謝謝。這是一個很好的答案。 – 2014-09-26 20:41:18