程序中,经常用到这种,就是需要固定时间执行的,或者需要每隔一段时间执行的。这里经常用的就是Timer定时器。Thread 类有一个 Timer子类,该子类可用于控制指定函数在特定时间内执行一次。
可以用几个例子来说明Timer的用法,
一 最简单的用法,N s后(2s)后执行:
1 #python3 example 2 from threading import Timer 3 import time 4 5 6 def hello_test(): 7 print("hello world") 8 9 t = Timer(2.0,hello_test) 10 t.start()
运行结果:
➜ timer git:(master) ✗ py timer_test1.py
hello world
二 每隔一秒执行一次,执行十次:
1 #python3 example 2 from threading import Timer 3 import time 4 5 count = 0 6 def print_timer(): 7 global t, count 8 print("count:%d new time: %s" % (count,time.ctime())) 9 count += 1 10 11 if count < 10: 12 t = Timer(1, print_timer) 13 t.start() 14 15 t = Timer(1.0, print_timer) 16 t.start()
运行结果:
1 ➜ timer git:(master) ✗ py timer_test2.py 2 count:0 new time: Tue Aug 20 14:20:13 2019 3 count:1 new time: Tue Aug 20 14:20:14 2019 4 count:2 new time: Tue Aug 20 14:20:15 2019 5 count:3 new time: Tue Aug 20 14:20:16 2019 6 count:4 new time: Tue Aug 20 14:20:17 2019 7 count:5 new time: Tue Aug 20 14:20:18 2019 8 count:6 new time: Tue Aug 20 14:20:19 2019 9 count:7 new time: Tue Aug 20 14:20:20 2019 10 count:8 new time: Tue Aug 20 14:20:21 2019 11 count:9 new time: Tue Aug 20 14:20:22 2019
三 带参数输入的timer,每隔一秒执行一次,执行十次:
1 #python3 example 2 from threading import Timer 3 import time 4 5 def print_val(cnt): 6 print("cnt:%d new time: %s" % (cnt,time.ctime())) 7 cnt += 1 8 9 if cnt < 10: 10 t = Timer(1, print_val,(cnt,)) 11 t.start() 12 else: 13 return 14 15 t = Timer(2.0, print_val,(1,)) 16 t.start()
运行结果:
1 ➜ timer git:(master) ✗ py timer_test.py 2 cnt:1 new time: Tue Aug 20 14:23:31 2019 3 cnt:2 new time: Tue Aug 20 14:23:32 2019 4 cnt:3 new time: Tue Aug 20 14:23:33 2019 5 cnt:4 new time: Tue Aug 20 14:23:34 2019 6 cnt:5 new time: Tue Aug 20 14:23:35 2019 7 cnt:6 new time: Tue Aug 20 14:23:36 2019 8 cnt:7 new time: Tue Aug 20 14:23:37 2019 9 cnt:8 new time: Tue Aug 20 14:23:38 2019 10 cnt:9 new time: Tue Aug 20 14:23:39 2019
从上面的例子可以看出,timer的基本用法是比较简单的,这个是不是对你有用呢?
参考文档:
1 http://c.biancheng.net/view/2629.html
作者:虚生 出处:https://www.cnblogs.com/dylancao/ 以音频和传感器算法为核心的智能可穿戴产品解决方案提供商 ,提供可穿戴智能软硬件解决方案的设计,开发和咨询服务。 勾搭热线:邮箱:1173496664@qq.com weixin:18019245820 市场技术对接群:347609188 |
![]() |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
2018-08-20 C语言数组一种巧妙的使用方式