threading.Timer – repeat function every ‘n’ seconds

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):
        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)
# this will stop the timer

Leave a Comment