I'm having difficulties with the python timer and would greatly appreciate some advice or help :D
I'm not too knowledgeable of how threads work, but I just want to fire off a function every 0.5 seconds and be able to start and stop and reset the timer.
However, I keep getting
RuntimeError: threads can only be started once when I execute
threading.timer.start() twice. Is there a work around for this? I tried applying
threading.timer.cancel() before each start.
t=threading.timer(0.5,function) while True: t.cancel() t.start()
The best way is to start the timer thread once. Inside your timer thread you'd code the following
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
In the code that started the timer, you can then
set the stopped event to stop the timer.
stopFlag = Event() thread = MyThread(stopFlag) thread.start() # this will stop the timer stopFlag.set()
Using timer threads-
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()
this can be stopped by