python – threading.Timer – repeat function every n seconds
python – threading.Timer – repeat function every n seconds
The best way is to start the timer thread once. Inside your timer thread youd 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()
From 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
Usage:
@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()
Or heres the same functionality but as a standalone function instead of a decorator:
cancel_future_calls = call_repeatedly(60, print, Hello, World)
# ...
cancel_future_calls()
Heres how to do it without using threads.
python – threading.Timer – repeat function every n seconds
Improving a little on Hans Thens answer, we can just subclass the Timer function. The following becomes our entire repeat timer code, and it can be used as a drop-in replacement for threading.Timer with all the same arguments:
from threading import Timer
class RepeatTimer(Timer):
def run(self):
while not self.finished.wait(self.interval):
self.function(*self.args, **self.kwargs)
Usage example:
def dummyfn(msg=foo):
print(msg)
timer = RepeatTimer(1, dummyfn)
timer.start()
time.sleep(5)
timer.cancel()
produces the following output:
foo
foo
foo
foo
and
timer = RepeatTimer(1, dummyfn, args=(bar,))
timer.start()
time.sleep(5)
timer.cancel()
produces
bar
bar
bar
bar