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 回答
慕码人2483693
TA贡献1860条经验 获得超9个赞
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贡献1853条经验 获得超9个赞
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()
智慧大石
TA贡献1946条经验 获得超3个赞
import threadingdef 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 secondsstop.set() # stop the loopstop = function() # start new timer# ...stop.set()
cancel_future_calls = call_repeatedly(60, print, "Hello, World")# ...cancel_future_calls()
添加回答
举报
0/150
提交
取消