我希望每隔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()
发布于 2012-09-15 14:56:41
最好的方法是启动计时器线程一次。在您的计时器线程中,您将编写以下代码
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()
发布于 2013-05-04 06:40:03
来自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()
发布于 2014-06-30 18:29:32
使用计时器线程-
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()
停止
https://stackoverflow.com/questions/12435211
复制相似问题