Python Timer定时器:控制函数在特定时间执行
发布时间:2025-10-13 17:52:51

Thread类有一个Timer子类,可以在特定时间内控制指定函数一次。例如,以下程序:
fromthreadingimportTimer
defhello():
print("hello,world")
#执行hello函数10秒后指定
t=Timer(10.0,hello)
t.start()使用上述程序 Timer 控制 10s 后执行 hello 函数。
需要注意的是,Timer 如果要使用,只能在指定时间内执行一次控制函数 Timer 如果控制函数多次重复执行,则需要执行下一次调度。
若要取消程序 Timer 可调用的调度 Timer 对象的 cancel() 函数。例如,下面的程序通常是 1s 当前时间输出一次:
fromthreadingimportTimer
importtime
#定义计数器总共输出几次
count=0
defprint_time():
print("当前时间:%:%s"%time.ctime())
globalt,count
count+=1
#如果count小于10,则开始下一次调度
ifcount<10:
t=Timer(1,print_time)
t.start()
#指定1秒后执行print_time函数
t=Timer(1,print_time)
t.start()上述程序开始运行后,程序控制 1s 后执行 print_time() 函数。print_time() 如果函数中的代码被判断, count 小于 10、程序再次使用 Timer 调度 1s 后执行 print_time() 这样就可以控制函数了 print_time() 函数多次重复执行。在上述程序中,因为只有当 count 小于 10 时才会使用 Timer 调度 1s 后执行 print_time() 因此,函数只会重复执行 10 次。
下一篇 面向对象之深度优先和广度优先
