Categories
Python Answers

How to repeat function every n seconds with Python threading.Timer?

Spread the love

Sometimes, we want to repeat function every n seconds with Python threading.Timer.

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

How to repeat function every n seconds with Python threading.Timer?

To repeat function every n seconds with Python threading.Timer, we can create a Thread subclass to run the code that we want to repeat.

For instance, we write

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

to create the MyThread class which is a subclass of the Thread class.

Then run method is run when the thread is started.

We run the repeated code with

while not self.stopped.wait(0.5):
   print("my thread")
   # ...

Then we write

stop_flag = Event()
thread = MyThread(stop_flag)
thread.start()
# ...
stop_flag.set()

to create the stop_flag with the Event class.

We create the thread with

thread = MyThread(stop_flag)

Then we start the thread with

thread.start()

And we stop the thread with

stop_flag.set()

Conclusion

To repeat function every n seconds with Python threading.Timer, we can create a Thread subclass to run the code that we want to repeat.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *