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.