? ? 程序中,經常用到這種,就是需要固定時間執行的,或者需要每隔一段時間執行的。這里經常用的就是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
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

