时间:2022-07-26 10:03:18 | 栏目:Python代码 | 点击:次
pip install retrying
from retrying import retry @retry() def say(): try: autofelix except Exception as e: # 可以将错误记录日志 print(e) raise say()
from retrying import retry @retry(stop_max_attempt_number=5) def say(): try: autofelix except Exception as e: # 可以将错误记录日志 print(e) raise say()
stop_max_delay
设置失败重试的最大时间, 单位毫秒from retrying import retry @retry(stop_max_delay=1000) def say(): try: autofelix except Exception as e: # 可以将错误记录日志 print(e) raise say()
from retrying import retry @retry(wait_fixed=1000) def say(): try: autofelix except Exception as e: # 可以将错误记录日志 print(e) raise say()
from retrying import retry @retry(wait_random_min=5000, wait_random_max=50000) def say(): try: autofelix except Exception as e: # 可以将错误记录日志 print(e) raise say()
wait_exponential_multiplier
间隔时间倍数增加wait_exponential_max
最大间隔时间from retrying import retry @retry(wait_exponential_multiplier=1000, wait_exponential_max=10000) def say(): try: autofelix except Exception as e: # 可以将错误记录日志 print(e) raise say()
retry_on_exception
设置指定异常类型wrap_exception
参数为True
,则其他类型异常from retrying import retry def retry_error(exception): return isinstance(exception, RetryError) # 会重复调用 @retry(etry_on_exception=retry_error) def say(): try: autofelix except RetryError as e: raise RetryError # 只调用一次 @retry(etry_on_exception=retry_error, wrap_exception=True) def say(): raise Exception('a') say()
retry_on_result
指定哪些结果需要去回调retry_on_result
指定方法中进行过滤,如果返回None,则继续回调,否则就结束from retrying import retry def retry_filter(result): print("this is result") return result is not None @retry(retry_on_result=retry_filter) def say(): print('Retry forever ignoring Exceptions with no wait if return value is None') return None say()
stop_func
每次抛出异常时都会执行的函数stop_max_delay
、stop_max_attempt_number
配合使用,则后两者会失效from retrying import retry def stop_record(attempts, delay): print("logging %d--->%d" % (attempts,delay)) @retry(stop_max_delay=10, stop_func=stop_record) def say(): print("i am autofelix") raise Exception say()