-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Playing with retries. #2040
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Playing with retries. #2040
Changes from 1 commit
2dc08cf
1de7a5c
49b3027
c532444
f33b2ea
e06815d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import time | ||
| from functools import wraps | ||
|
|
||
|
|
||
| def retry(exception, tries=4, delay=3, backoff=2, logger=None): | ||
| """Retry calling the decorated function using an exponential backoff. | ||
|
|
||
| :type exception: Exception or tuple | ||
This comment was marked as spam.
Sorry, something went wrong. |
||
| :param exception: the exception to check. may be a tuple of | ||
| exceptions to check | ||
This comment was marked as spam.
Sorry, something went wrong. |
||
|
|
||
| :type tries: int | ||
| :param tries: number of times to try (not retry) before giving up | ||
|
|
||
| :type delay: int | ||
| :param delay: initial delay between retries in seconds | ||
|
|
||
| :type backoff: int | ||
| :param backoff: backoff multiplier e.g. value of 2 will double the delay | ||
| each retry | ||
This comment was marked as spam.
Sorry, something went wrong. |
||
|
|
||
| :type logger: logging.Logger instance | ||
| :param logger: logger to use. If None, print | ||
|
|
||
| :rtype: func | ||
| :returns: Retry wrapper function. | ||
| """ | ||
| def retry_decorator(f): | ||
This comment was marked as spam.
Sorry, something went wrong. |
||
|
|
||
| @wraps(f) | ||
| def f_retry(*args, **kwargs): | ||
| mtries, mdelay = tries, delay | ||
| while mtries > 1: | ||
| try: | ||
| return f(*args, **kwargs) | ||
| except exception as e: | ||
This comment was marked as spam.
Sorry, something went wrong. |
||
| msg = "%s, Retrying in %d seconds..." % (str(e), mdelay) | ||
| if logger: | ||
| logger.warning(msg) | ||
| else: | ||
| print(msg) | ||
This comment was marked as spam.
Sorry, something went wrong. |
||
| time.sleep(mdelay) | ||
| mtries -= 1 | ||
| mdelay *= backoff | ||
| return f(*args, **kwargs) | ||
|
|
||
| return f_retry | ||
|
|
||
| return retry_decorator | ||
This comment was marked as spam.
Sorry, something went wrong. |
||
This comment was marked as spam.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This comment was marked as spam.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.