连续触发定时器 RepeatTimer

本文介绍了一个Python库中对`threading.Timer`的扩展,创建了一个名为`RepeatTimer`的类,允许重复启动和停止,且在函数执行时间长于间隔时仅执行一次。同时提到了使用递归方式可能导致的内存问题。

Python threading.Timer 是个单次触发定时器,即,调用 start 后只能触发一次,且 start 只能调用一次。

参考了部分网文,进行了如下简单封装,可以重复调用 start 和 stop,且可以获取运行状态。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec  6 13:55:20 2023

@author: farman
"""

from threading import Timer


class _RepeatTimer(Timer):
    """
    Repeat version of threading.Timer
    """
    def run(self):
        while not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
            self.finished.wait(self.interval)
        return


class RepeatTimer:
    """
    All operations are same to threading.Timer EXCEPT the below:
        (1) while the timer is started, the custom function will be executed 
            repeatly.
        (2) if the time consumption of the custom function is longer than
            the repeat interval, the custom function only executed once after
            once, no overlap will occured.
    
    __init__(self, interval, function, args
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值