租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

Python定时器Timer如何使用

发布时间:2023-10-26 11:21:16

Python定时器Timer如何使用

在Python中,可使用Timer类实现定时器功能。Timer类位于threading模块中,可以创建一个定时器对象,设置定时器的时间间隔和履行的函数,然后启动定时器。

下面是Timer类的基本使用方法:

  1. 导入threading模块。
import threading
  1. 定义一个函数作为定时器的履行函数。
def my_function():
    print("定时器履行的函数")
  1. 创建一个Timer对象,设置定时器的时间间隔和履行的函数。
my_timer = threading.Timer(5.0, my_function)
  1. 启动定时器。
my_timer.start()

完全的代码示例:

import threading

def my_function():
    print("定时器履行的函数")

my_timer = threading.Timer(5.0, my_function)
my_timer.start()

上述代码中,定时器将在5秒后履行my_function函数,并输出"定时器履行的函数"。

需要注意的是,定时器对象创建后需要手动启动,才能开始计时和履行定时任务。另外,Timer类的构造函数有两个参数,第一个参数是定时器的时间间隔,单位是秒;第二个参数是定时器要履行的函数。