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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。