Timer object in Python with example

In this tutorial, you will learn briefly about timer object in python with relevant information. Firstly, 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.

In general, Timer object is used to implement scheduled tasks which supposed to be executed only after a certain instant of time. Also, it’s not necessary that the Timer object will be executed exactly after the scheduled time as after that the python interpreter looks for a thread to execute the timer object task, which if  not available leads to more waiting.

The Syntax for creating Timer object

Below the syntax for the Timer class constructor is displayed:

threading.Timer(interval, function, args=[], kwargs={})

Create a timer that will run 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.
  • cancel() method.

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.

import threading 
def gfg():
    print("Helloworld!\n")
timer = threading.Timer(2.0, gfg)
time.start()
print("Exit\n")

Output:

Exit

Helloworld!

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 it’s action yet.

import threading 
def gfg():
    print("Helloworld!")
timer = threading.Timer(5.0, gfg)
timer.start()
print("Cancelling timer\n")
timer.cancel()
print("Exit\n")

Output:

Cancelling timer
Exit

Example for Timer Object :

Below we have a very simple example where we create a timer object and start it.

import threading 
def task():
    print("timer object..")
if __name__=='__main__':
    t = threading.Timer(10, task)
    t.start()

The above program is a simple program, now let’s use the cancel to cancel the the timert object tasks execution.

import threading 
import time

def task():
    print("Timer object is getting executed...")

if __name__=='__main__':
    t=threading.Timer(5, task)
    print("Starting the timer object..")
    t.start()
    print("cancelling the timer object")
    t.cancel()

Output:

Starting the timer object..
cancelling the timer object

In the above program, first comment the code on line number 11 and 12 and run the program, then uncomment those lines and see the cancel() method in action.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top