Python threading.timer-每'n'秒重复一次函数

发布于 2021-02-02 23:15:33

我想每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()
关注者
0
被浏览
115
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

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

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看