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()
python定时器装饰器
于 2024-01-03 13:45:55 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)