打印

test08.py

[复制链接]
281|0
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
laojun001|  楼主 | 2025-2-25 21:47 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
08, PY, TEST, or, TI, he
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.

使用特权

评论回复

相关帖子

发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

15

主题

23

帖子

1

粉丝