-
Notifications
You must be signed in to change notification settings - Fork 78
/
retry.py
36 lines (28 loc) · 1.07 KB
/
retry.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import time
from functools import wraps
from utility.log import Log
logger = Log(__name__)
def retry(exception_to_check, tries=4, delay=3, backoff=2):
"""
Retry calling the decorated function using exponential backoff.
Args:
exception_to_check: the exception to check. may be a tuple of exceptions to check
tries: number of times to try (not retry) before giving up
delay: initial delay between retries in seconds
backoff: backoff multiplier e.g. value of 2 will double the delay each retry
"""
def deco_retry(f):
@wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
while mtries > 1:
try:
return f(*args, **kwargs)
except exception_to_check as e:
logger.warning("%s, Retrying in %d seconds..." % (str(e), mdelay))
time.sleep(mdelay)
mtries -= 1
mdelay *= backoff
return f(*args, **kwargs)
return f_retry
return deco_retry