代码示例:
import time
def retry_with_time_accumulator(fn):
def wrapper(*args, **kwargs):
retry = 3 # 最大重试次数
while retry > 0:
try:
result = fn(*args, **kwargs)
return result
except Exception as e:
print("Error occurred:", str(e))
print("Retrying after 5 seconds...")
time.sleep(5)
retry -= 1
print("All retries failed.")
return wrapper
@retry_with_time_accumulator
def example_function():
# 假设这个功能可能会导致错误
# 这里放入可能会出错的代码
pass
以上代码定义了一个名为retry_with_time_accumulator
的装饰器函数,它将对传入的函数进行重试,并在每次重试前暂停5秒钟。上述示例中,重试次数最大限制为3次,之后会打印出“全部重试失败”的消息。
此后,您可以在需要进行重试的任何函数上使用该装饰器。例如,我们使用@retry_with_time_accumulator
来修饰example_function()
。这将使该函数在出现错误时进行重试。