Created
February 4, 2020 21:54
-
-
Save srleyva/ae8550e4214129f61875f55951dc9512 to your computer and use it in GitHub Desktop.
Pluggable backoff class
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 | |
class BackOff: | |
def __init__(self, backoff_type='fib', retries=10): | |
self._backoff_type = backoff_type | |
self.retries = retries | |
self._backoff_generator = None | |
@property | |
def backoff_type(self): | |
return self._backoff_type | |
@backoff_type.setter | |
def backoff_type(self, backoff_type): | |
self._backoff_type = backoff_type | |
self._backoff_generator = None | |
@property | |
def backoff_generator(self): | |
if self._backoff_generator is None: | |
try: | |
self._backoff_generator = getattr(self, self.backoff_type) | |
except AttributeError: | |
raise AttributeError(f'No backoff type: {self.backoff_type}') | |
return self._backoff_generator | |
def retry(self, func): | |
def wrapper(*args, **kwargs): | |
exception = None | |
for count, wait in enumerate(self.backoff_generator(self.retries)): | |
print(f'Retry {count} waiting for {wait} seconds') | |
time.sleep(wait) | |
try: | |
res = func(*args, **kwargs) | |
break | |
except Exception as ex: | |
exception = ex | |
continue | |
else: | |
raise exception | |
return res | |
return wrapper | |
def fib(self, n): | |
a, b = 0, 1 | |
for _ in range(n+1): | |
yield a | |
a,b = b, a + b | |
def exponential(self, n): | |
a = 0 | |
for n in range(n+1): | |
yield a | |
a = n ** 2 | |
if __name__ == '__main__': | |
backoff = BackOff() | |
@backoff.retry | |
def print_hello(n=5): | |
print('Hello, world!') | |
raise Exception | |
print_hello() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment