當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python Timer cancel()用法及代碼示例


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