Python Timer.cancel() 方法
cancel() 是 Python 中线程模块的 Timer 类的内置方法。
Timer 类对象代表必须在给定时间过后才能执行的操作。这个类是Thread类的子类。该类中的 Cancel() 方法用于停止定时器和取消定时器对象的执行。只有当计时器仍在等待区域时,动作才会停止。
模块:
from threading import Timer
用法:
cancel()
参数:
- None
返回值:
这个方法的返回类型是<class 'NoneType'>
.该方法不返回任何内容。它用于在线程等待期间取消线程。
范例1:
# 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")
输出:
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
范例2:
# 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")
输出:
Starting the timer object Value printed= 19 This time thread is not cancelled as 3 seconds have passed when cancel() method is called
相关用法
- Python Timer start()用法及代码示例
- Python Thread join()用法及代码示例
- Python Tensorflow asin()用法及代码示例
- Python Thread run()用法及代码示例
- Python Tensorflow nn.sigmoid()用法及代码示例
- Python TextBlob.correct()用法及代码示例
- Python Tensorflow math.accumulate_n()用法及代码示例
- Python Tensorflow cosh()用法及代码示例
- Python TextCalendar prmonth()用法及代码示例
- Python Tensorflow acos()用法及代码示例
- Python Tensorflow asinh()用法及代码示例
- Python Tensorflow nn.softplus()用法及代码示例
- Python Tensorflow exp()用法及代码示例
- Python Tensorflow logical_and()用法及代码示例
- Python Tensorflow logical_or()用法及代码示例
- Python TextCalendar formatyear()用法及代码示例
- Python Sympy Triangle.is_right()用法及代码示例
- Python Tensorflow atanh()用法及代码示例
- Python TextBlob.Word.spellcheck()用法及代码示例
- Python Tensorflow bitwise.bitwise_and()用法及代码示例
注:本文由纯净天空筛选整理自 Python Timer Class | cancel() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。