Python线程计时器-每n‘秒重复一次函数我在python计时器上遇到了困难,非常希望得到一些建议或帮助:d我不太了解线程是如何工作的,但我只想每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()
3 回答
烙印99
TA贡献1829条经验 获得超13个赞
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()
慕慕森
TA贡献1856条经验 获得超17个赞
from threading import Timer,Thread,Eventclass 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()
添加回答
举报
0/150
提交
取消