Timer objects are used to create some actions which are bounded by the time period. Using timer object create some threads that carries out some actions. In python Timer is a subclass of Thread class. Using start() method timer is started.
Creating a Timer object
threading.Timer(interval, function, args = None, kwargs = None), this is the syntax of creating timer of Timer object.
Here in this example at first we shall get
Bye
After 3 second it will display
Python program
Example
import threading def mytimer(): print("Python Program\n") my_timer = threading.Timer(3.0, mytimer) my_timer.start() print("Bye\n")
Output
Bye Python Program
Cancelling a timer
timer.cancel() is the syntax for cancelling the timer.
Example
import threading def mytimer(): print("Python Program\n") my_timer = threading.Timer(3.0, mytimer) my_timer.start() print("Cancelling timer\n") my_timer.cancel() print("Bye\n")
Output
Cancelling Timer Bye