【问题标题】:Ruby - timeout not workingRuby - 超时不起作用
【发布时间】:2016-11-04 13:48:54
【问题描述】:

我希望这段代码运行不超过 5 秒:

require 'httpi'
require 'timeout'

puts Time.new
begin
    request,response=nil,nil
    Timeout::timeout(5){
        request=HTTPI::Request.new(url: "http://example.com")
        response=HTTPI.get(request)
    }
rescue 
    puts "except: #{$!}"
ensure
    puts Time.new
end

但这是我得到的输出:

2016-11-04 09:44:55 -0400
D, [2016-11-04T09:44:55.916557 #2476] DEBUG -- : HTTPI GET request to example.com (net_http)
except: execution expired
2016-11-04 09:45:16 -0400

我假设 NET 的默认 HTTP 超时时间是 20 秒,所以 Timeout::timeout 只是允许代码运行它想要的时间。为什么?

【问题讨论】:

    标签: ruby timeout


    【解决方案1】:

    正如您所看到的hereherehere,Ruby 的Timeout 模块以存在一些问题而闻名。

    你应该考虑不要使用这个模块,除非它是非常必要的。

    相反,您可以使用 HTTPI API 提供的 read_timeout 和/或 open_timeout 选项。

    request = HTTPI::Request.new(url: "http://example.com")
    request.open_timeout = 5 # seconds
    request.read_timeout = 5 # seconds
    response = HTTPI.get(request)
    

    【讨论】:

      猜你喜欢
      • 2017-08-07
      • 2018-12-27
      • 2012-05-15
      • 2011-02-21
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多