Home >Backend Development >Python Tutorial >How to Maintain Control Over Repeating Functions Using Python's threading.Timer?

How to Maintain Control Over Repeating Functions Using Python's threading.Timer?

Barbara Streisand
Barbara StreisandOriginal
2024-11-09 18:37:02469browse

How to Maintain Control Over Repeating Functions Using Python's threading.Timer?

Threading.Timer - Maintaining Control over Repeating Functions

Python's threading.Timer provides a mechanism to schedule functions to run at specified time intervals. However, the initial approach using multiple calls to start() can lead to runtime errors.

To resolve this issue, it's recommended to create a custom thread class, as demonstrated in the solution below:

import threading

class MyThread(threading.Thread):
    def __init__(self, event, function):
        threading.Thread.__init__(self)
        self.stopped = event
        self.function = function

    def run(self):
        while not self.stopped.wait(0.5):
            self.function()

In this class, the stopped event is used to control the thread's execution. Instead of starting and stopping the timer multiple times, the thread continuously runs, checking the stopped event at regular intervals. When the event is set, the thread terminates.

In the code that initiated the timer, you can then use the stopped event to stop the timer:

stopFlag = threading.Event()
thread = MyThread(stopFlag, function)
thread.start()

# To stop the timer later on
stopFlag.set()

This approach provides a clean and efficient way to start, stop, and reset the timer, allowing for flexible control over recurring function executions.

The above is the detailed content of How to Maintain Control Over Repeating Functions Using Python's threading.Timer?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn