Created
February 20, 2013 07:40
-
-
Save DeLaGuardo/4993707 to your computer and use it in GitHub Desktop.
Decorator "retry" with backoff.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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