First, the Timer class basic introduction
This class indicates that an action should run after a specific time--that is, a timer. A timer is a subclass of thread, so you can also use functions to create custom threads.
Class Threading. Timer (interval, function, args=[], kwargs={})
Creates a timer that, after interval seconds, will run function with the parameter args and keyword parameters Kwargs.
Second, simple example # Coding:utf-8 from threading import Timer def fun (): print "Hello, world" if __name__== ' __main__ ': t = Ti Mer (5.0, Fun) T.start () # 5 seconds later, "Hello, World" will be printed
Third, cancel thread execution
timers starts as a thread by calling their start () method. A timer can stop by calling the Cancel () method before its action begins. The time interval that a timer waits before executing its action may not be exactly the same as the time interval specified by the user. Cancel
()
stops the timer and cancels execution of the timer action. This works only when the timer is still in the waiting phase.
# Coding:utf-8
from threading import Timer
def fun ():
print "Hello, world"
if __name__== ' __main__ ':
T = Timer (5.0, Fun)
T.start () # starts execution thread, but does not print "Hello, World"
T.cancel () # Because cancel cancels the execution of the thread, the fun () function will not be executed