import logging
import time
from functools import wraps
from time import sleep
class Retry:
"""
类装饰器,当函数执行抛出异常时,按照max_retries和wait_time重试
"""
def __init__(self, max_retries=3, wait_time=2):
self.max_retries = max_retries
self.wait_time = wait_time
def __call__(self, func):
@wraps(func)
def wrapper(*args, **kwargs):
attempts = 0
while attempts < self.max_retries:
try:
return func(*args, **kwargs)
except Exception as e:
attempts += 1
logging.error(f"Error occurred: {e}. Retrying {attempts}/{self.max_retries}...")
time.sleep(self.wait_time) # 等待惩罚时间
if attempts == self.max_retries:
logging.error("Max retries reached. Giving up.")
return wrapper
@Retry(max_retries=5, wait_time=1)
def say_hello():
print("Hello!")
sleep(0.2)
raise Exception("手动抛出异常")
say_hello()
# Hello!
# ERROR:root:Error occurred: 手动抛出异常. Retrying 1/5...
# Hello!
# ERROR:root:Error occurred: 手动抛出异常. Retrying 2/5...
# Hello!
# ERROR:root:Error occurred: 手动抛出异常. Retrying 3/5...
# Hello!
# ERROR:root:Error occurred: 手动抛出异常. Retrying 4/5...
# Hello!
# ERROR:root:Error occurred: 手动抛出异常. Retrying 5/5...
# ERROR:root:Max retries reached. Giving up.
|