Python Threading Single-threaded timer repeating call function

Source: Internet
Author: User
Tags thread class

A timer is required in the project, and each time a constructor function call is used:

timer = threading.Timer(timerFlag, upload_position)timer.start()   

After the print thread is discovered, a new child thread is created each time, although there is only one active thread, but it is also a waste of resources:

  print ("Threading active = {} \ n \ nthe". Format (Threading.enumerate ())) #打印threading active = [ <_mainthread (Mainthread, stopped 140735596835712), <timer (Thread-1, started 123145498161152);] Threading active = [<_mainthread (Mainthread, stopped 140735596835712);, <timer (Thread-1, started 123145498161152) >]threading active = [<_mainthread (Mainthread, stopped 140735596835712);, <timer ( Thread-1, started 123145498161152) >]threading active = [<_mainthread (Mainthread, stopped 140735596835712); <timer (Thread-2, started 123145503416320) >]threading active = [<_mainthread (Mainthread, stopped 140735596835712), <timer (Thread-2, started 123145503416320) >]threading active = [<_mainthread ( Mainthread, stopped 140735596835712), <timer (Thread-3, started 123145498161152) >]threading active = [<_ Mainthread (Mainthread, stopped 140735596835712), <timer (Thread-3, started 123145498161152);]  

Read the source code and documentation

class Timer(Thread):    """Call a function after a specified number of seconds:            t = Timer(30.0, f, args=None, kwargs=None)            t.start()            t.cancel()     # stop the timer's action if it's still waiting    """    def __init__(self, interval, function, args=None, kwargs=None):        Thread.__init__(self)        self.interval = interval        self.function = function        self.args = args if args is not None else []        self.kwargs = kwargs if kwargs is not None else {}        self.finished = Event()    def cancel(self):        """Stop the timer if it hasn't finished yet."""        self.finished.set()    def run(self):        self.finished.wait(self.interval)        if not self.finished.is_set():            self.function(*self.args, **self.kwargs)        self.finished.set()# Special thread class to represent the main thread# This is garbage collected through an exit handler

found that, in fact, the timer is a subclass of threading, with wait to achieve the timing effect, binding the entry function, so the code is modified as follows

def startTimer():    global timer    if timer != None:        timer.finished.wait(timerFlag)        timer.function()       else:        timer = threading.Timer(timerFlag, upload_position)        timer.start()

Printing results:

threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]
Always have only one thread and call the function method repeatedly ~end~

? ?
? ?
? ?

Links: personal website??????? Technical Blog??????? Jane Book homepage

Python Threading Single-threaded timer repeating call function

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.