Compile a simple timer in Python and a timer in python.

Source: Internet
Author: User

Compile a simple timer in Python and a timer in python.

The following describes how to implement a timer using the threading module.

First, we will introduce a simple implementation:

import threadingdef say_sth(str):  print str  t = threading.Timer(2.0, say_sth,[str])  t.start()if __name__ == '__main__':  timer = threading.Timer(2.0,say_sth,['i am here too.'])  timer.start()

It is unclear whether there are any defects in some special application scenarios.

The following describes 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 an action at the end of the timer run.       """       def __init__(self, seconds, action, args=[]):           self.args = args           self.action = action           CountDownTimer.__init__(self, seconds)       def run(self):           CountDownTimer.run(self)           self.action(self.args)      def myAction(args=[]):       print "Performing my action with args:"       print args   if __name__ == "__main__":       t = CountDownExec(3, myAction, ["hello", "world"])       t.start() 

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.