2014-09-26 46 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