当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。