Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- import itertools
- # tested with https://www.onlinegdb.com/online_python_compiler
- def retry(delays=(0, 1, 5, 30, 60), exception=Exception):
- """Repeats a function until the timeout, fail (Exception) or success
- the first retry is done immediately (after 0 seconds),
- the next retry after 1 second,
- the next after 5 seconds,
- then 30 seconds,
- then 1 minute,
- Parameters
- ----------
- delays: list
- time in seconds between retries.
- exception: Exception
- exception to monitor
- Returns
- -------
- None
- Raises
- ------
- Exception
- Examples
- --------
- >>> @retry()
- >>> def divisaoPorZero(): return 1 / 0
- >>> divisaoPorZero()
- Tentativa de executar a operação: division by zero -- nova tentativa em 0 segundos.
- Tentativa de executar a operação: division by zero -- nova tentativa em 1 segundos.
- Tentativa de executar a operação: division by zero -- nova tentativa em 5 segundos.
- Tentativa de executar a operação: division by zero -- nova tentativa em 30 segundos.
- Tentativa de executar a operação: [ZeroDivisionError('division by zero',)]
- -- nova tentativa em 1 segundos.
- Tentativa de executar a operação: [ZeroDivisionError('division by zero',)]
- -- nova tentativa em 5 segundos.
- See Also
- --------
- http://code.activestate.com/recipes/580745-retry-decorator-in-python/?in=lang-python
- """
- def wrapper(function):
- def wrapped(*args, **kwargs):
- for delay in itertools.chain(delays, [ None ]):
- try:
- return function(*args, **kwargs)
- except exception as e:
- if delay is None:
- print("Tentativa de executar a operação: {}.\n".format(e))
- else:
- print("Tentativa de executar a operação: {} -- nova tentativa em {} segundos.\n".format(e,delay))
- time.sleep(delay)
- return wrapped
- return wrapper
- @retry()
- def divisaoPorZero():
- return 1 / 0
- divisaoPorZero()
Advertisement
Add Comment
Please, Sign In to add comment