Python 的 'threading.Timer' 类可以用于在一定时间后执行函数,但是默认情况下 timer 只会运行一次。如果需要重复运行 timer,需要在函数内部重新启动一个新的 timer,或者使用循环来控制 timer 的运行次数。

以下是一个简单的示例:

import threading

def hello():
    print('Hello, world!')
    # 重新启动 timer,间隔时间为 2 秒
    t = threading.Timer(2.0, hello)
    t.start()

# 启动 timer,间隔时间为 2 秒
t = threading.Timer(2.0, hello)
t.start()

这样,'hello' 函数就会每隔 2 秒执行一次,直到程序结束或者手动停止。

Python threading.Timer: 如何实现重复执行

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

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