Python定时器如何精确控制函数在指定时间点执行?

2026-06-11 11:261阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计408个文字,预计阅读时间需要2分钟。

Python定时器如何精确控制函数在指定时间点执行?

pythonclass ThreadWithTimer: def __init__(self, func, time): self.timer=threading.Timer(time, func)

def start(self): self.timer.start()

from threading import Timer

def hello(): print(hello, world)

Thread 类有一个 Timer子类,该子类可用于控制指定函数在特定时间内执行一次。例如如下程序:

from threading import Timer def hello(): print("hello, world") # 指定10秒后执行hello函数 t = Timer(10.0, hello) t.start() 上面程序使用 Timer 控制 10s 后执行 hello 函数。

需要说明的是,Timer 只能控制函数在指定时间内执行一次,如果要使用 Timer 控制函数多次重复执行,则需要再执行下一次调度。

如果程序想取消 Timer 的调度,则可调用 Timer 对象的 cancel() 函数。

阅读全文

本文共计408个文字,预计阅读时间需要2分钟。

Python定时器如何精确控制函数在指定时间点执行?

pythonclass ThreadWithTimer: def __init__(self, func, time): self.timer=threading.Timer(time, func)

def start(self): self.timer.start()

from threading import Timer

def hello(): print(hello, world)

Thread 类有一个 Timer子类,该子类可用于控制指定函数在特定时间内执行一次。例如如下程序:

from threading import Timer def hello(): print("hello, world") # 指定10秒后执行hello函数 t = Timer(10.0, hello) t.start() 上面程序使用 Timer 控制 10s 后执行 hello 函数。

需要说明的是,Timer 只能控制函数在指定时间内执行一次,如果要使用 Timer 控制函数多次重复执行,则需要再执行下一次调度。

如果程序想取消 Timer 的调度,则可调用 Timer 对象的 cancel() 函数。

阅读全文