Home >Backend Development >Python Tutorial >How to Implement a Recurring Function with 'threading.Timer' Without the 'RuntimeError: threads can only be started once' Issue?

How to Implement a Recurring Function with 'threading.Timer' Without the 'RuntimeError: threads can only be started once' Issue?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-12 05:13:01719browse

How to Implement a Recurring Function with 'threading.Timer' Without the 'RuntimeError: threads can only be started once' Issue?

Implementing a Recurring Function with 'threading.Timer'

Creating a function that runs repeatedly every 'n' seconds is a common requirement in programming. However, using 'threading.Timer' for this purpose can present challenges.

One approach involves starting a timer thread multiple times, as shown in the pseudo code below:

t=threading.timer(0.5,function)
while True:
    t.cancel()
    t.start()

However, this may result in a 'RuntimeError: threads can only be started once' error because 'threading.Timer' objects can only be started once. To address this, we can create a custom thread class that handles the repeated execution and cancellation of the timer:

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")
            # call a function

In the main code, we can create an event to control the timer thread:

stopFlag = Event()
thread = MyThread(stopFlag)
thread.start()
# this will stop the timer
stopFlag.set()

By using this approach, we can start and stop the recurring function as needed, without encountering the 'RuntimeError' issue.

The above is the detailed content of How to Implement a Recurring Function with 'threading.Timer' Without the 'RuntimeError: threads can only be started once' Issue?. 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