From: Joel VanderWerf Date: 2010-02-23T04:47:37+09:00 Subject: Re: Ruby Idiom To Retry open() Upto N Times Before Giving Up Dan wrote: > I write a lot of scripts that I run once or infrequently that uses open-rui. Occasionally I run into a web site that times out or is unavailable for a period of time. My normal solution is to just rerun the script manually at a later time and the problem goes away. What I would like to start doing is rescuing the open() and retrying the open() after a delay. What would be the most idiomatic way to try opening a url say n times before giving up? Here is my crude code for trying twice: > > begin > open("http://www.example.com/foo.html") > rescue > begin > open("http://www.example.com/foo.html") > rescue > #tried twice - giving up > end > end > > I would like a more general approach using ruby idioms where I could specify the maximum number of attempts and delay before giving up. Thanks for your help. Another approach (minus the delay part): $ cat open-with-retry.rb def open_with_retry uri, tries=3 catch :success do tries.times do |i| begin throw :success, open(uri) rescue => e puts "try ##{i}: #{e}" end end raise "Giving up" end end f = open_with_retry(ARGV[0]) puts f.read $ ruby open-with-retry.rb readme.txt this is a file $ ruby open-with-retry.rb noexist try #0: No such file or directory - noexist try #1: No such file or directory - noexist try #2: No such file or directory - noexist open-with-retry.rb:10:in `open_with_retry': Giving up (RuntimeError) from open-with-retry.rb:2:in `catch' from open-with-retry.rb:2:in `open_with_retry' from open-with-retry.rb:14