Blog Post RSS ?

Blogs » Ruby on Rails » Timing out and retrying calls to third parties
 

Timing out and retrying calls to third parties


  • Save to
    Del.icio.us

by Tim Lucas

When calling third parties you want to set them a sensible timeout, and you also might want to make a few attempts before giving up. Here’s a relatively succinct way to accomplish this in Ruby (3 attempts, each with a timeout of 5 seconds):


3.times do
  begin
    Timeout::timeout(5) do
      # Call your third party (for a example, a payment gateway)
    end
    @success = true
    break
  rescue Exception
    # Try again!
  end
end

if @success
  # Jump for joy!
end

I’m sure somebody will chime in with an even sexier way…

This post has 3 responses so far

  1. def with_timeout(attempts = 3, timeout = 5)
      attempts.times do
        begin
          Timeout::timeout(timeout) do
            yield
          end
          return true
        rescue Exception
        end
      end
    end

    =>

    with_timeout do
      # ...
    end
     
  2. Fenrir2, instead of catching all the exceptions would you not be better just to catch the Timeout::Error exception?

    I mean, if the code in the yield really has a problem you want to know about it…

     
  3. Fenrir2: nice abstraction of my code :)

    myrdhrin: In my case I didn’t care watch was being thrown, but might be handier would be if you could pass in a array of exceptions to ignore.

    retry_with_timeout(:ignoring => [Timeout::Error, SomeOtherError]) { ... }

    There must be a way to make it sexier, say:

    3.times { try_with_timeout(5.seconds, :ignoring => SomeOtherError) { ... } }

    (the internal timeout should specify and catch its own timeout exception as well as SomeOtherError)

    I’ll have a play this evening and see if I can whip that up.

     

Sponsored Links

Leave a response

You are not logged in, log in with your SitePoint Forum username and password.

-OR- Post Anonymously

* Make sure any code samples are escaped (i.e. ‘<b>’ becomes ‘&lt;b&gt;’).

If not logged in, your comments will be placed in a moderation queue. This means your comment may not appear until one of our moderators approves it.

SitePoint Marketplace

Buy and sell Websites, templates, domain names, hosting, graphics and more.

Logo Design, Web page Design and more!

99designs

  • Custom logo designs created ‘just for you’.
  • Pick the design you like best.
  • Only pay if you’re satisfied with the result.

Want More Traffic?

Get up to five quotes from qualified SEO specialists, with no obligation!

Get A Free SEO Quote Now!