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 ()