作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我想每 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/
我是一名优秀的程序员,十分优秀!