Last active
September 9, 2016 03:53
-
-
Save lvsmart/8188930306224be4882e4231a1737cdf to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
| import math | |
| def retry(tries, delay=3, backoff=2): | |
| if backoff <= 1: | |
| raise ValueError("backoff must be greater than 1") | |
| tries = math.floor(tries) | |
| if tries < 0: | |
| raise ValueError("tries must be 0 or greater") | |
| if delay <= 0: | |
| raise ValueError("delay must be greater than 0") | |
| def deco_retry(f): | |
| def f_retry(*args, **kwargs): | |
| mtries, mdelay = tries, delay # make mutable | |
| rv = f(*args, **kwargs) # first attempt | |
| while mtries > 0: | |
| if rv is True: # Done on success | |
| return True | |
| mtries -= 1 # consume an attempt | |
| time.sleep(mdelay) # wait... | |
| mdelay *= backoff # make future wait longer | |
| rv = f(*args, **kwargs) # Try again | |
| return False # Ran out of tries :-( | |
| return f_retry # true decorator -> decorated function | |
| return deco_retry # @retry(arg[, ...]) -> true decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment