注意
- 安装
- 重试次数包括第一次执行, 即重试 3 次就是执行 3 次
示例
无任何限制
from tenacity import *
@retry
def aaa():
print(123)
raise Exception
aaa()
重试次数
from tenacity import *
@retry(stop=stop_after_attempt(2))
def aaa():
print(123)
raise Exception
aaa()
重试时间限制(总数)
from tenacity import *
@retry(stop=stop_after_delay(5))
def aaa():
print(123)
raise Exception
aaa()
“|” 的使用
from tenacity import *
@retry(stop=(stop_after_delay(5)|stop_after_attempt(3)))
def aaa():
print(123)
raise Exception
aaa()
重试前等待
from tenacity import *
@retry(wait=wait_fixed(2))
def aaa():
print(123)
raise Exception
aaa()
坑点注意
- wait_fixed 是重试前等待, 重试实际已经开始
- 如下示例:
- 超时 5 秒, 执行前等待 4 秒
- 第一次执行, 约为 0 秒, 失败, 重试
- 第二次执行, 等待 4 秒, 失败, 此时仍在 5 秒内, 所以继续重试
- 第三次执行, 等待 4 秒, 失败, 抛出错误
- 实际执行时间会超过 5 秒
- 如果执行前等待为 5 秒, 则重试两次就会触发 5 秒的超时限制, 直接抛出错误
from tenacity import *
@retry(stop=(stop_after_delay(5)|stop_after_attempt(3)), wait=wait_fixed(4))
def aaa():
print(123)
sleep(2)
raise Exception
aaa()
自定义重试规则
from tenacity import *
def is_false(v):
"""
当 v 为 false 时返回 True
:param v:
:return:
"""
return v is False
@retry(retry=retry_if_result(is_false), stop=stop_after_attempt(3), wait=wait_fixed(2))
def aaa():
return False
aaa()
返回函数结果
def return_last_value(retry_state):
return retry_state.outcome.result()
@retry(retry=retry_if_result(is_false), stop=(stop_after_delay(10)|stop_after_attempt(3)), wait=wait_fixed(2), retry_error_callback=return_last_value)
def aaa():
print(123)
sleep(2)
return False
aaa()