Skip to content

Instantly share code, notes, and snippets.

@DeLaGuardo
Created February 20, 2013 07:40
Show Gist options
  • Save DeLaGuardo/4993707 to your computer and use it in GitHub Desktop.
Save DeLaGuardo/4993707 to your computer and use it in GitHub Desktop.
Decorator "retry" with backoff.
import time
from functools import wraps
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None):
def deco_retry(f):
@wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
while mtries > 1:
try:
return f(*args, **kwargs)
except ExceptionToCheck, e:
msg = "%s, Retrying in %s seconds..." % (str(e), mdelay)
if logger:
logger.warning(msg)
else:
print msg
time.sleep(mdelay)
mtries -= 1
mdelay *= backoff
return f(*args, **kwargs)
return f_retry # true decorator
return deco_retry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment