Home »
Python »
Python Reference »
Python Timer Class
Python Timer cancel() Method with Example
Python Timer.cancel() Method: In this tutorial, we will learn about the cancel() method of Timer Class in Python with its usage, syntax, and examples.
By Hritika Rajput Last updated : April 23, 2023
Python Timer.cancel() Method
The Timer.cancel() method is used to stop the timer and cancel the timer object execution. The action will be stopped only when the timer is still in the waiting area.
Module
The following module is required to use cancel() method:
import threading
Class
The following class is required to use cancel() method:
from threading import Timer
Syntax
The following is the syntax of cancel() method:
cancel()
Parameter(s)
The following are the parameter(s):
Return Value
The return type of this method is <class 'NoneType'>. The method does not return anything. It is used to cancel a thread during its waiting time.
Example 1: Use of Timer.cancel() Method in Python
# python program to explain the
# use of cancel() method in Timer class
import threading
def helper_function(i):
print("Value printed=",i)
if __name__=='__main__':
thread1 = threading.Timer(interval = 3, function = helper_function,args = (9,))
print("Starting the timer object")
print()
# Starting the function after 3 seconds
thread1.start()
print("This gets printed before the helper_function as helper_function starts after 3 seconds")
print()
# This cancels the thread when 3 seconds
# have not passed
thread1.cancel()
print("Thread1 cancelled, helper_function is not executed")
Output
Starting the timer object
This gets printed before the helper_function as helper_function starts after 3 seconds
Thread1 cancelled, helper_function is not executed
Example 2: Use of Timer.cancel() Method in Python
# python program to explain the
# use of cancel() method in Timer class
import threading
import time
def helper_function(i):
print("Value printed=",i)
print()
if __name__=='__main__':
thread1 = threading.Timer(interval = 3, function = helper_function,args = (19,))
print("Starting the timer object")
print()
# Starting the function after 3 seconds
thread1.start()
# Sleeping this thread for 5 seconds
time.sleep(5)
# This will not cancel the thread as 3 seconds have passed
thread1.cancel()
print("This time thread is not cancelled as 3 seconds have passed when cancel() method is called")
Output
Starting the timer object
Value printed= 19
This time thread is not cancelled as 3 seconds have passed when cancel() method is called