Fri, 15 Feb 2008

Ruby Tidbit: Timeout code execution

Posted by Ben Fri, 15 Feb 2008 00:39:00 GMT

Just a small tip, if you wish to ensure a snippet of Ruby code doesn’t run for too long you can use the timeout function. You might want to do this when making a request to a remote server with net/http for example.

timeout.rb

A way of performing a potentially long-running operation in a thread, and terminating it‘s execution if it hasn‘t finished within fixed amount of time.

Here’s a quick example using the excellent rFeedParser (Universal Feed Parser in Ruby) to fetch an RSS feed.

require 'timeout'
require 'zlib'
require 'rubygems'
require 'rfeedparser'

fp = nil
begin
  # Don't take longer than 20 seconds to retrieve & parse an RSS feed
  Timeout::timeout(20) do
    fp = FeedParser.parse("http://feeds.feedburner.com/slashdotdash")
  end
rescue Timeout::Error
  # Too slow!!
end