Improve current implementation of a setInterval
Solution 1:
To call a function repeatedly with interval
seconds between the calls and the ability to cancel future calls:
from threading import Event, Thread
def call_repeatedly(interval, func, *args):
stopped = Event()
def loop():
while not stopped.wait(interval): # the first call is in `interval` secs
func(*args)
Thread(target=loop).start()
return stopped.set
Example:
cancel_future_calls = call_repeatedly(60, print, "Hello, World")
# ...
cancel_future_calls()
Note: this version waits around interval
seconds after each call no matter how long func(*args)
takes. If metronome-like ticks are desired then the execution could be locked with a timer()
: stopped.wait(interval)
could be replaced with stopped.wait(interval - timer() % interval)
where timer()
defines the current time (it may be relative) in seconds e.g., time.time()
. See What is the best way to repeatedly execute a function every x seconds in Python?