A code snippet: Controlled retry

H

Hal Fulton

I sometimes find myself retrying operations when in a networked
situation (e.g., maybe server isn't up, just try again).

I just wrote this little bit of code.

Tell me what you think... I'm sure it can be improved.

Cheers,
Hal


def try(quiet=true,times=5,secs=1,&block)
count = 0
catch :finished do
begin
block.call
rescue => err
puts "Error was: #{err}" if not quiet
count += 1
throw :finished if count > times
sleep secs
retry
end
end
end
 
G

Gennady

def try(quiet=true,times=5,secs=1,&block)
count = 0
catch :finished do
begin
block.call
rescue => err
puts "Error was: #{err}" if not quiet
count += 1
throw :finished if count > times
sleep secs
retry
end
end
end


def try(quiet=true,times=5,secs=1,&block)
return unless block
times.times do
begin
return block.call
rescue => err
puts "Error was: #{err}" unless quiet
sleep secs
end
end
end


Sincerely,
Gennady Bystritsky
 
G

Gennady

def try(quiet=true,times=5,secs=1,&block)
return unless block
times.times do
begin
return block.call
rescue => err
puts "Error was: #{err}" unless quiet
sleep secs
end
end
end

Oops, times.times should become times.next.times to function like the
original. Also, when all attempts are exhausted, the last exception
must be re-raised or another more appropriate one raised (boolean
return would also do the trick).
 
R

Robert Klemme

Gennady said:
Oops, times.times should become times.next.times to function like the
original. Also, when all attempts are exhausted, the last exception
must be re-raised or another more appropriate one raised (boolean
return would also do the trick).

Combining the two of them (i.e. times.next and re-raising) by simply
adding a line,
plus adding a check to allow for non-sleeping retries,
plus output parameter that can be an IO or an Array,
plus changed the first return to an exception in order to let the user
know he forgot something:

def try(times=0, secs=nil, log=nil, &block)
raise LocalJumpError, "no block given" unless block

times.times do
begin
return block.call
rescue => err
log << "Error was: #{err}\n" if log
sleep secs if secs
end
end

block.call
end

Cheers

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,165
Latest member
JavierBrak
Top