Python 中线程定时器可以使用 threading.Timer 类来实现。以下是使用方法:

  1. 导入 threading 模块:
import threading
  1. 创建定时器对象:
timer = threading.Timer(interval, function, args=None, kwargs=None)

其中,interval 表示定时器间隔时间,function 表示定时器到期时要执行的函数,argskwargs 是函数的参数。

  1. 启动定时器:
timer.start()
  1. 取消定时器:
timer.cancel()

完整的示例代码如下:

import threading

def print_hello():
    print("Hello, world!")

timer = threading.Timer(5.0, print_hello)
timer.start()

以上代码会在 5 秒后输出 "Hello, world!"

python 中 线程定时器如何使用

原文地址: https://www.cveoy.top/t/topic/g68p 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录