程序中,经常用到这种,就是需要固定时间执行的,或者需要每隔一段时间执行的。这里经常用的就是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