发布时间:2025-12-09 12:05:31 浏览次数:13
cancel() 是 Python 中线程模块的 Timer 类的内置方法。
Timer 类对象代表必须在给定时间过后才能执行的操作。这个类是Thread类的子类。该类中的 Cancel() 方法用于停止定时器和取消定时器对象的执行。只有当计时器仍在等待区域时,动作才会停止。
模块:
from threading import Timer
用法:
cancel()
参数:
返回值:
这个方法的返回类型是<class 'NoneType'>.该方法不返回任何内容。它用于在线程等待期间取消线程。
范例1:
# python program to explain the# use of cancel() method in Timer classimport threadingdef 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")输出:
Starting the timer objectThis gets printed before the helper_function as helper_function starts after 3 secondsThread1 cancelled, helper_function is not executed
范例2:
# python program to explain the# use of cancel() method in Timer classimport threadingimport timedef 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")输出:
Starting the timer objectValue printed= 19This time thread is not cancelled as 3 seconds have passed when cancel() method is called