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

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

被折叠的 条评论
为什么被折叠?



