python 中 线程定时器如何使用
Python 中线程定时器可以使用 threading.Timer 类来实现。以下是使用方法:
- 导入
threading模块:
import threading
- 创建定时器对象:
timer = threading.Timer(interval, function, args=None, kwargs=None)
其中,interval 表示定时器间隔时间,function 表示定时器到期时要执行的函数,args 和 kwargs 是函数的参数。
- 启动定时器:
timer.start()
- 取消定时器:
timer.cancel()
完整的示例代码如下:
import threading
def print_hello():
print("Hello, world!")
timer = threading.Timer(5.0, print_hello)
timer.start()
以上代码会在 5 秒后输出 "Hello, world!"
原文地址: https://www.cveoy.top/t/topic/g68p 著作权归作者所有。请勿转载和采集!