• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python Timer定时器:控制函数在特定时间执行

python 搞java代码 3年前 (2022-05-21) 40次浏览 已收录 0个评论

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

from threading import Timer

def <a href="https://www.gaodaima.com/tag/hello" title="查看更多关于hello的文章" target="_blank">hello</a>():
    print("hello, world")
# 指定10秒后执行hello函数
t = Timer(10.0, hello)
t.start()

www#gaodaima.com来源gao!%daima.com搞$代*!码$网搞代码

上面程序使用 Timer 控制 10s 后执行 hello 函数。

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

如果程序想取消 Timer 的调度,则可调用 Timer 对象的 cancel() 函数。例如,如下程序每 1s 输出一次当前时间:

from threading import Timer
import time

# 定义总共输出几次的计数器
count = 0
def print_time():
    print("当前时间:%s" % time.ctime())
    global t, count
    count += 1
    # 如果count小于10,开始下一次调度
    if count < 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 次。

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python Timer定时器:控制函数在特定时间执行
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址