others - python threading.timer 每'n'秒重复函数

我不知道线程是如何工作的,想每0.5秒启动一个函数,并且能够启动和停止。

但是我一直在 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()

等效于python中的setInterval :


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


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

使用计时器线程-


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

...