Created
July 30, 2012 21:50
-
-
Save Ceasar/3210626 to your computer and use it in GitHub Desktop.
Retry a function until it succeeds or has failed a given number of times.
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 functools | |
import time | |
ef retry(exceptions, tries=5, delay=0.25): | |
"""Retry the decorated function using an exponential backoff strategy. | |
If the function does not complete successfully after the specified number | |
of tries, the exception is raised normally.""" | |
def wrapper(func): | |
@functools.wraps(func) | |
def wrapped(*args, **kwargs): | |
mtries, mdelay = tries, delay | |
while mtries > 0: | |
try: | |
return func(*args, **kwargs) | |
except exceptions, e: | |
print "%s" % e | |
waited = mdelay | |
while waited > 0: | |
msg = 'Retrying in {0} seconds...\r'.format(waited) | |
sys.stdout.write(msg) | |
sys.stdout.flush() | |
time.sleep(1) | |
waited -= 1 | |
sys.stdout.write("\r%s\r" % (' ' * len(msg))) | |
mdelay += mdelay | |
mtries -= 1 | |
if mtries == 0: | |
raise e | |
return wrapped | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment