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'
  SystemTimer.timeout_after(2.seconds) do
    @sock = TCPSocket.new(host, port)
rescue Timeout::Error
  @sock = nil
  raise Timeout::Error, "Timeout connecting to the server"

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.