Object timer in Python

Python Methods and Functions

Timer is a subclass of the Thread class defined in python. It starts with an explicit call to the start () function corresponding to the timer.

Create Timer


  threading.Timer (interval, function, args = None, kwargs = None)  

Create a timer that will run the function with args and keyword arguments kwargs after an interval of seconds has elapsed. If args is None (the default), then an empty list will be used. If kwargs is None (default) then an empty dict will be used.

# Program for demonstration
# python timer objects


import threading

def gfg ():

print ( "GeeksforGeeks" )


timer = threading.Timer ( 2.0 , gfg)

timer.start ()

print < code class = "plain"> ( "Exit" )


 Exit Python.Engineering 

Explanation: The above program schedules the gfg () function to run 5 seconds after the start () function is called.

Cancel timer

Syntax :


Stop the timer and cancel the execution of the timer action. This will only work if the timer is still pending.

# Program to cancel the timer

import threading


def gfg ():

print ( "GeeksforGeeks" )


timer = threading.Timer ( 5.0 , gfg)

timer.start ()

print ( " Cancelling timer " )

timer.cancel ()

print ( "Exit" )


 Cancelling timer Exit 

This article courtesy of Mayank Kumar . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please write in comments if you find anything wrong or if you'd like to share more information on the topic discussed above.