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:
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.
irb(main):017:0> attempts = 3
=> 3
irb(main):018:0> begin
irb(main):019:1* raise "Error, attempt = #{attempts}"
irb(main):020:1> rescue => e
irb(main):021:1> puts e
irb(main):022:1> attempts -= 1
irb(main):023:1> retry if attempts > 0
irb(main):024:1> puts "giving up"
irb(main):025:1> end
Error, attempt = 3
Error, attempt = 2
Error, attempt = 1
giving up
=> nil
irb(main):026:0>
Kind regards
robert
···
On 22.02.2010 19:53, 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:
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.
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:
def open_with_retry(url, n=10, delay=1)
1.upto(n) do
begin
open(url) do |handle|
yield handle
end
break
rescue
puts "Sleeping ..."
sleep delay
end
end
end
Note that this sleeps even if the last attempt failed.
Marcelo
···
On Mon, Feb 22, 2010 at 12:53, Dan <dandiebolt@yahoo.com> wrote:
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.