Skip to content

Instantly share code, notes, and snippets.

@lktslionel
Created December 16, 2021 22:27
Show Gist options
  • Save lktslionel/3ba1576504f150fed5bd09c81edaae3e to your computer and use it in GitHub Desktop.
Save lktslionel/3ba1576504f150fed5bd09c81edaae3e to your computer and use it in GitHub Desktop.
Exponential BackOff implemented in python
import time
DEFAULT_TIMEOUT_IN_SEC = 1
DEFAULT_MAX_ATTEMPTS = 5
def retry(**kwargs):
def inner(func):
attempt = 0
max_attempts = kwargs["attempts"] if kwargs["attempts"] else DEFAULT_MAX_ATTEMPTS
timeout = kwargs["timeout"] if kwargs["timeout"] else DEFAULT_TIMEOUT_IN_SEC
while attempt < max_attempts:
try:
func()
break
except Exception as e:
print("ERROR: {}\n".format(e))
attempt = attempt + 1
timeout = 1 + (attempt * timeout)
print(
"{}/{} attempts. Retrying after {}s...".format(
attempt, max_attempts, timeout
)
)
time.sleep(timeout)
return inner
@retry(attempts=3, timeout=1)
def process():
print("\nprocessing...")
raise Exception("Cloud function failed")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment