通常为了防止程序出现异常而终止,我们会采用try来获取异常。
列如调用第三方API,设备状态心跳上报网络不稳定都可能发生异常。
我们希望当程序发生异常时能自动重复调用或者指定调用次数等。
python retrying库,完美的实现这个需求。
retrying 提供一个装饰器函数 retry,被装饰的函数会在运行失败的情况下重新执行,默认一直报错就一直重试。
安装库 pip install retrying
1.无限重试from retrying import retry
import time
@retry()
def run():
print('重复调用')
time.sleep(1)
raise Exception
2.最大重试次数 stop_max_attempt_number
@retry(stop_max_attempt_number=5)
def run():
print('重复调用')
time.sleep(1)
raise Exception
3.最大重试时间 stop_max_delay 单位毫秒
@retry(stop_max_delay=5000)
def run():
print('重复调用')
time.sleep(1)
raise Exception
4.重试间隔时间 wait_fixed 单位毫秒
@retry(wait_fixed=5000)
def run():
print('重复调用')
raise Exception
5.重试同时调用其他方法 stop_func
#参数 attempts, delay必填项
def log_error(attempts, delay):
print('记录异常')
#指定异常重复调用函数
@retry(stop_func=log_error)
def run():
print('重复调用')
time.sleep(1)
raise Exception
if __name__ == '__main__':
run()



