python定时器装饰器

本文介绍了一个使用Python装饰器和`threading`库实现的定时任务功能,通过`threading.Event`来控制定时器的暂停和继续,展示了如何创建一个每秒执行一次的`my_function`定时任务,并能手动停止。
摘要由CSDN通过智能技术生成
import functools
import threading
import time


def timed_function(interval, thread_status):
    """
    在函数上加上一下内容就可以实现定时器
    thread_status = threading.Event()  # 用于停止定时器,执行thread_status.set()就可以停止该定时器
    @timed_function(interval=0.01, thread_status=thread_status)
    """

    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # 定义定时器回调函数
            def timer_callback():
                func(*args, **kwargs)
                # 递归调用定时器,实现周期性执行
                if not thread_status.is_set():
                    threading.Timer(interval, timer_callback).start()

            # 启动定时器
            threading.Timer(interval, timer_callback).start()

        return wrapper

    return decorator


# 用于停止定时器,执行thread_status.set()就可以停止该定时器,interval是定时器间隔
thread_status = threading.Event()
@timed_function(interval=1, thread_status=thread_status)
def my_function():
    print(f"定时器触发 - 执行函数")


if __name__ == '__main__':
    # 调用 my_function,获取定时器对象,每一秒执行一次
    my_function()
    # 休眠十秒
    time.sleep(10)
    # 设置事件,停止定时器
    thread_status.set()

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值