A way to write a simple timer in Python

Source: Internet
Author: User
The following is a method of implementing timers with the threading module.

Let's start by introducing one of the simplest implementations:

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 what is defective in some special application scenarios.

The following is the implementation of the timer class to be introduced:

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 Co Unter Time.sleep (1.0) Counter-= 1 Print "Done" Class Countdownexec (Countdownti       MER): "" 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 (sel F.args) def myaction (args=[]): print "Performing my action with args:" Print args if __name__ = = "__main__": t = countdownexec (3, M  Yaction, ["Hello", "World"]) T.start ()
  • 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.