kehtyr
kehtyr

Reputation: 47

Ruby - timeout not working

I'm expecting this piece of code to run for no longer than 5 seconds:

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

But this is the output I'm getting:

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

I'm assuming NET's default HTTP timeout is 20 seconds, so Timeout::timeout is just allowing the code to run however long it wants. Why?

Upvotes: 0

Views: 402

Answers (1)

Lucas Costa
Lucas Costa

Reputation: 1129

As you can see here, here and here, the Ruby's Timeout module is famous for having some problems.

You should consider not using this module, unless it is extremely necessary.

Instead, you can use the read_timeout and/or open_timeout options provided by the HTTPI's API.

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

Upvotes: 2

Related Questions