Skip to content

Instantly share code, notes, and snippets.

@zmej-serow
Last active June 14, 2023 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmej-serow/0e64e17e68bdb173233337189cde5dfb to your computer and use it in GitHub Desktop.
Save zmej-serow/0e64e17e68bdb173233337189cde5dfb to your computer and use it in GitHub Desktop.
Retrying decorator with customizable delay between attempts
from functools import wraps
from random import randrange
from time import sleep
def retry(retry_limit=3, delay=None, max_random_delay=600):
"""
Retrying decorator with simple backoff logic.
:param retry_limit: amount of retries before throwing exception
:param delay: delay between attempts in seconds. If None, random delay each time
:param max_random_delay: maximum random delay in seconds
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
retries = 0
while retries < retry_limit:
try:
print(f'trying to execute {func.__name__}: {retries + 1}/{retry_limit}')
return func(*args, **kwargs)
except Exception as e:
retries += 1
if retries == retry_limit:
raise e
if delay is None:
sleep_time = randrange(max_random_delay)
print(f'sleep for {sleep_time} seconds')
sleep(sleep_time)
else:
print(f'sleep for {delay} seconds')
sleep(delay)
return wrapper
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment