加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程 > 正文

Python Timer定时器:控制函数在规定时间实施

发布时间:2021-05-29 12:27:01 所属栏目:编程 来源:互联网
导读:Thread 类有一个 Timer子类,该子类可用于节制指定函数在特按时刻内执行一次。譬喻如下措施: from threading import Timer def hello (): print ( hello, world

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() 函数。譬喻,如下措施每 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 次。

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读