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

Patricia Arquette
Release: 2024-11-12 05:13:01
Original
669 people have browsed it

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()
Copy after login

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
Copy after login

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()
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template