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


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

Python Timer.start() 方法

start() 是 Python 中線程模塊的 Timer 類的內置方法。

Timer 類對象代表必須在給定時間過後才能執行的操作。該類是 Thread 類的子類。 Start() 方法,這裏是用來啟動定時器的。當這個方法被調用時,定時器對象啟動它的定時器,並且在給定的間隔時間過去之後,函數被執行。

模塊:

    from threading import Timer

用法:

    start()

參數:

  • None

返回值:

這個方法的返回類型是<class 'NoneType'>.該方法不返回任何內容。它用於啟動 Timer 類的線程。

範例1:

# python program to explain the
# use of start() 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()

輸出:

Starting the timer object

This gets printed before the helper_function as helper_function starts after 3 seconds

Value printed= 9

範例2:

# python program to explain the
# use of start() 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


相關用法


注:本文由純淨天空篩選整理自 Python Timer Class | start() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。