Timeout Web Service Calls in Ruby 1.8 [tip]

Nothing new, but something I ran into recently with Ruby 1.8 and its conditionally working (more info) version of Timeout is a better implementation called SystemTimer.

While my use case was for opening TCP connections in daemon workers, it is even more critical in any blocking Rails code that uses external service calls (web service/external memcached/fulltext search/nosql cluster/etc). It’s easy enough to do and will save you from bottlenecks in the event one of you external properties or 3rd parties is not responsive.

Use it

require 'system_timer'
begin
  SystemTimer.timeout_after(2.seconds) do
    @sock = TCPSocket.new(host, port)
  end
rescue Timeout::Error
  @sock = nil
  raise Timeout::Error, "Timeout connecting to the server"
end

Leave a Reply

Your email address will not be published. Required fields are marked *