blog comments 0 del.icio.us bookmarks 0 diggs 0 Google results 0

5.8
PostRank

Ruby Tidbit: Timeout code execution

From Slash Dot Dash, 9 months ago, 0 views

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

comments

No comments yet.

You must be logged in to add your own comment.