Python threading.timer-每'n'秒重复一次函数
我想每0.5秒触发一次功能,并且能够启动,停止和重置计时器。我不太了解Python线程的工作方式,并且在使用python计时器时遇到了困难。
但是,RuntimeError: threads can only be started once
当我执行threading.timer.start()
两次时,我会不断得到帮助。有没有解决的办法?我尝试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
然后,在启动计时器的代码中,可以
set
停止事件来停止计时器。stopFlag = Event() thread = MyThread(stopFlag) thread.start() # this will stop the timer stopFlag.set()