Timer Object - Python Multithreading
Timer objects are created using Timer
class which is a subclass of the Thread
class. Using this class we can set a delay on any action that should be run only after a certain amount of time has passed(timer) and can easily be cancelled during that delay.
Timers are started, just like normal threads, by calling their start()
method. A timer thread can be stopped (before its action has begun) by calling its cancel()
method.
Timer object is generally used to implement scheduled tasks which supposed to be executed only after a certain instant of time.
Also, its not necessary that the Timer object will be executed exactly after the scheduled time as after that the python intrepreter looks for a thread to execute the timer object task, which if not available leads to more waiting.
Syntax for creating Timer object
Following is the syntax for the Timer
class constructor:
threading.Timer(interval, function, args=[], kwargs={})
This way we can create a timer object that will run the function with arguments args
and keyword arguments kwargs
, after interval
seconds have passed.
Methods of Timer
class
In the Timer
class we have two methods used for starting and cancelling the execution of the timer object.
start()
method
This method is used to start the execution of the timer object. When we call this method, then the timer object starts its timer.
cancel()
method
This method is used to stop the timer and cancel the execution of the timer object's action. This will only work if the timer has not performed its action yet.
Time for an Example
Below we have a simple example where we create a timer object and start it.
import threading
def task():
print("timer object task running...")
if __name__=='__main__':
t = threading.Timer(10, task)
t.start() # after 10 seconds, task will be executed
The above program is a simple program, now let's use the cancel method to cancel the timer object task's execution.
In the program above, first comment the code on line number 13 and 14 and run the program, then uncomment those lines and see the cancel()
method in action.