threading.Timer - 每“n”秒重复一次函数

新手上路,请多包涵

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

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

伪代码:

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

原文由 user1431282 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 790
2 个回答

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

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()

原文由 Hans Then 发布,翻译遵循 CC BY-SA 3.0 许可协议

Hans Then 的回答 稍作改进,我们可以将 Timer 函数子类化。以下成为我们的 整个“重复计时器”代码,它可以用作具有所有相同参数的 threading.Timer 的直接替换:

 from threading import Timer

class RepeatTimer(Timer):
    def run(self):
        while not self.finished.wait(self.interval):
            self.function(*self.args, **self.kwargs)

使用示例:

 def dummyfn(msg="foo"):
    print(msg)

timer = RepeatTimer(1, dummyfn)
timer.start()
time.sleep(5)
timer.cancel()

产生以下输出:

 foo
foo
foo
foo

timer = RepeatTimer(1, dummyfn, args=("bar",))
timer.start()
time.sleep(5)
timer.cancel()

产生

bar
bar
bar
bar

原文由 right2clicky 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题