Skip to content

Instantly share code, notes, and snippets.

@leechannl
Created November 23, 2012 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leechannl/4134388 to your computer and use it in GitHub Desktop.
Save leechannl/4134388 to your computer and use it in GitHub Desktop.
Roll to get the ultimate answer of life, universe, and everything.
import time
import math
import random
import sys
# Retry decorator with exponential backoff
def retry(tries, delay=3, backoff=2):
'''Retries a function or method until it returns True.
delay sets the initial delay in seconds, and backoff sets the factor by which
the delay should lengthen after each failure. backoff must be greater than 1,
or else it isn't really a backoff. tries must be at least 0, and delay
greater than 0.'''
if backoff <= 1:
raise ValueError("backoff must be greater than 1")
tries = math.floor(tries)
if tries < 0:
raise ValueError("tries must be 0 or greater")
if delay <= 0:
raise ValueError("delay must be greater than 0")
def deco_retry(f):
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay # make mutable
rv = f(*args, **kwargs) # first attempt
while mtries > 0:
if rv is True: # Done on success
return True
mtries -= 1 # consume an attempt
for i in range(mdelay):
time.sleep(1)
sys.stdout.write('.')
sys.stdout.flush()
print ""
time.sleep(mdelay) # wait...
mdelay += backoff # make future wait longer
rv = f(*args, **kwargs) # Try again
return False # Ran out of tries :-(
return f_retry # true decorator -> decorated function
return deco_retry # @retry(arg[, ...]) -> true decorator
@retry(15, 3, 2)
def roll_the_ultimate_answer():
if random.randint(1, 100) == 42:
print "Congratulations, you got the answer!"
print "42"
return True
else:
print "bang!"
print roll_the_ultimate_answer()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment