Menu Close

How to repeat a function every ‘n’ seconds with Python threading.timer?

Sometimes, we want to repeat a function every ‘n’ seconds with Python threading.timer.

In this article, we’ll look at how to repeat a function every ‘n’ seconds with Python threading.timer.

How to repeat a function every ‘n’ seconds with Python threading.timer?

To repeat a function every ‘n’ seconds with Python threading.timer, we can create a subclass of Thread and call the start method on the subclass instance.

For instance, we write:

from threading import Timer, Thread, Event


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")


stopFlag = Event()
thread = MyThread(stopFlag)
thread.start()

We creatr the MyThread class which inherits from Thread.

In the class, we have the stopped property which is set to event.

And we have the run method with code that runs repeatedly.

We keep running the while loop until the stopFlag.set() is called.

Then we create an instance of MyThread with stopFlag as the argument.

And we call start on the thread.

Now we should see "my thread" repeatedly.

Conclusion

To repeat a function every ‘n’ seconds with Python threading.timer, we can create a subclass of Thread and call the start method on the subclass instance.

Posted in Python, Python Answers