Ruby Net::HTTP Timeout

1,315 views
Skip to first unread message

kim chirnside

unread,
Jun 24, 2008, 1:10:01 AM6/24/08
to ChicagoRuby.org
I'm attempting to get a rails action to remotely post to another rails
action on the site's sister server. However, I need to assert that
the HTTP post will timeout if a connection cannot be made to the
remote server. Here's roughly what my code looks like so far:

url = URI.parse(REMOTE_URI)
url.path = "/" if url.path.length < 1
req = Net::HTTP::Post.new(url.path)
req.set_form_data({ :id => params[:id],
:name => params[:name], ';')

res = Net::HTTP.new(url.host, url.port).start do |http|
http.read_timeout = 5
http.request(req)
end

case res
when Net::HTTPSuccess
# success
else
# something went wront
end

The problem is that the http.request(req) is not timing out, if the
requestee is busy. I want it to give up quite quickly as this is not
a critical service. I look at the docs on Net::HTTP and found
read_timeout which I have set to 5 seconds. However this has done
nothing.

Does anyone know how to ensure that the http request does timeout if
the connection is busy?

Cheers,
Kim

Erik Peterson

unread,
Jun 25, 2008, 7:53:36 AM6/25/08
to kim chirnside, ChicagoRuby.org
Kim,

Check out Ruby's built-in timeout functionality. Here's an example with a timeout and multiple tries.

retries = 2

timeout(5) do

  res = Net::HTTP.new(url.host, url.port).start do |http|
    http.request(req)
  end
rescue Timeout::Error
  if retries > 0
    retries -= 1
    retry
  else
    # handle the timeout
  end
end

kim chirnside

unread,
Jun 25, 2008, 3:48:37 PM6/25/08
to ChicagoRuby.org
Thanks Erik. That's great!!

Didn't work initially. Until I tried it outside of irb. For some
reason Timeout::timeout does not seem to work in irb!! Now it is
gracefully continuing after 5 seconds. Perfect.

http://jerith.livejournal.com/40063.html had something to say
regarding problems with timeout and it mentions irb.

Kim

On Jun 25, 11:53 pm, "Erik Peterson" <thecompanygarde...@gmail.com>
wrote:
> Kim,
>
> Check out Ruby's built-in timeout functionality. Here's an example with a
> timeout and multiple tries.
>
> retries = 2
>
> timeout(5) do
>   res = Net::HTTP.new(url.host, url.port).start do |http|
>     http.request(req)
>   end
> rescue Timeout::Error
>   if retries > 0
>     retries -= 1
>     retry
>   else
>     # handle the timeout
>   end
> end
>
> On Tue, Jun 24, 2008 at 12:10 AM, kim chirnside <kimmy.chirns...@gmail.com>
Reply all
Reply to author
Forward
0 new messages