Home  >  Article  >  Backend Development  >  Why Does `threading.Timer` Raise a `RuntimeError` When Repeatedly Started?

Why Does `threading.Timer` Raise a `RuntimeError` When Repeatedly Started?

DDD
DDDOriginal
2024-11-10 17:20:03282browse

Why Does `threading.Timer` Raise a `RuntimeError` When Repeatedly Started?

Threading with a Repeating Timer

To periodically execute a function every 'n' seconds, the Python threading.Timer class offers a practical solution. However, using this timer can be tricky when you need to start, stop, and reset it repeatedly.

Suppose you want to fire a function every 0.5 seconds. You might try the following:

import threading

def function_to_execute():
    # Your function code here

t = threading.Timer(0.5, function_to_execute)

while True:
    t.cancel()
    t.start()

However, this code will raise a RuntimeError, complaining about starting a thread more than once. Why is that?

By default, the start() method of a timer thread can only be called once. But since we're canceling and restarting the timer repeatedly, we run into this issue.

Creating a Reusable Timer Thread

To overcome this limitation, a better approach is to start the timer thread only once. Inside the thread, we'll implement the recurring function execution:

import threading

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

    def run(self):
        while not self.stopped.wait(0.5):
            # Execute your function here

# Create a stop event
stopFlag = threading.Event()

# Start the timer thread
thread = MyThread(stopFlag)
thread.start()

With this setup, the timer thread will continuously execute the function every 0.5 seconds. To stop the timer, simply set the stopFlag event:

# Stop the timer
stopFlag.set()

Using this method, you can repeatedly start, stop, and reset the timer as needed, without encountering the RuntimeError.

The above is the detailed content of Why Does `threading.Timer` Raise a `RuntimeError` When Repeatedly Started?. 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