Home >Backend Development >Python Tutorial >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!