Python定时器Timer如何使用
在Python中,可使用Timer
类实现定时器功能。Timer
类位于threading
模块中,可以创建一个定时器对象,设置定时器的时间间隔和履行的函数,然后启动定时器。
下面是Timer
类的基本使用方法:
threading
模块。import threading
def my_function():
print("定时器履行的函数")
Timer
对象,设置定时器的时间间隔和履行的函数。my_timer = threading.Timer(5.0, my_function)
my_timer.start()
完全的代码示例:
import threading
def my_function():
print("定时器履行的函数")
my_timer = threading.Timer(5.0, my_function)
my_timer.start()
上述代码中,定时器将在5秒后履行my_function
函数,并输出"定时器履行的函数"。
需要注意的是,定时器对象创建后需要手动启动,才能开始计时和履行定时任务。另外,Timer
类的构造函数有两个参数,第一个参数是定时器的时间间隔,单位是秒;第二个参数是定时器要履行的函数。
TOP