gpt4 book ai didi

python - threading.Timer - 每 'n' 秒重复一次函数

转载 作者:IT老高 更新时间:2023-10-28 21:34:20 30 4
gpt4 key购买 nike

我想每 0.5 秒触发一次功能,并能够启动和停止以及重置计时器。我不太了解 Python 线程的工作原理,并且在使用 Python 计时器时遇到了困难。

但是,当我执行 threading.timer.start() 两次时,我不断收到 RuntimeError: threads can only start once。有解决办法吗?我尝试在每次开始之前应用 threading.timer.cancel()

伪代码:

t=threading.timer(0.5,function)
while True:
t.cancel()
t.start()

最佳答案

最好的方法是启动一次定时器线程。在您的计时器线程中,您将编写以下代码

class MyThread(Thread):
def __init__(self, event):
Thread.__init__(self)
self.stopped = event

def run(self):
while not self.stopped.wait(0.5):
print("my thread")
# call a function

在启动计时器的代码中,您可以设置停止的事件来停止计时器。

stopFlag = Event()
thread = MyThread(stopFlag)
thread.start()
# this will stop the timer
stopFlag.set()

关于python - threading.Timer - 每 'n' 秒重复一次函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12435211/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com