Python threading.timer-每隔“n”秒重复一次函数

2024-04-26 10:38:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想每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()

Tags: 函数onlybe线程startcancancel计时器
3条回答

来自Equivalent of setInterval in python

import threading

def setInterval(interval):
    def decorator(function):
        def wrapper(*args, **kwargs):
            stopped = threading.Event()

            def loop(): # executed in another thread
                while not stopped.wait(interval): # until stopped
                    function(*args, **kwargs)

            t = threading.Thread(target=loop)
            t.daemon = True # stop if the program exits
            t.start()
            return stopped
        return wrapper
    return decorator

用法:

@setInterval(.5)
def function():
    "..."

stop = function() # start timer, the first call is in .5 seconds
stop.set() # stop the loop
stop = function() # start new timer
# ...
stop.set() 

或者这里是the same functionality but as a standalone function instead of a decorator

cancel_future_calls = call_repeatedly(60, print, "Hello, World")
# ...
cancel_future_calls() 

Here's how to do it without using threads

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

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

使用计时器线程-

from threading import Timer,Thread,Event


class perpetualTimer():

   def __init__(self,t,hFunction):
      self.t=t
      self.hFunction = hFunction
      self.thread = Timer(self.t,self.handle_function)

   def handle_function(self):
      self.hFunction()
      self.thread = Timer(self.t,self.handle_function)
      self.thread.start()

   def start(self):
      self.thread.start()

   def cancel(self):
      self.thread.cancel()

def printer():
    print 'ipsem lorem'

t = perpetualTimer(5,printer)
t.start()

这可以通过t.cancel()停止

相关问题 更多 >