Python's way to implement timer timer via thread _python

Source: Internet
Author: User

The example in this article describes the way Python implements timer timer by thread. Share to everyone for your reference. The specific analysis is as follows:

This Python class implements a timer effect, which is simple enough to allow the system to perform a specified function at timed intervals.

Here's how to implement the timer with the threading module.

Do a simple experiment before using:

Import Threading
def sayhello ():
    print "Hello World"
    global T    #Notice: Use global variable!
    t = Threading. Timer (5.0, SayHello)
    T.start ()
t = Threading. Timer (5.0, SayHello)
T.start ()

The results of the operation are as follows:

>python hello.py Hello World Hello World

The following is the implementation of the Timer class:

Class Timer (threading.
    Thread): "" "very simple but useless timer. "" "Def __init__ (self, seconds): Self.runtime = seconds Threading. Thread.__init__ (self) def run (self): Time.sleep (self.runtime) Print buzzzz!!
    Time ' s up! class Countdowntimer (timer): "" A timer that can counts down the seconds.
            "" "Def Run (self): Counter = Self.runtime for sec in range (Self.runtime): Print counter  Time.sleep (1.0) Counter-= 1 Print "Done" class Countdownexec (Countdowntimer): "" "A
    Timer that execute a action at the end of the timer run. "" "Def __init__ (self, Seconds, action, args=[]): Self.args = args self.action = Action Countd Owntimer.__init__ (self, seconds) def run (self): Countdowntimer.run (self) self.action (Self.args) def my Action (args=[]): print "Performing my action with args:" Print args if __name__ = = "__main__": t = countdownexec (3, myaction, ["Hello", "World"]) T.start () 

The above code runs through the Python 2.5.4.

I hope this article will help you with your Python programming.

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.