方法一、用time模塊中的sleep方法
import datetime
import time
def do_job():
while True:
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
time.sleep(2)
if __name__ == '__main__':
do_job()
輸出結果:
2020-01-17 23:41:28
2020-01-17 23:41:30
2020-01-17 23:41:32
2020-01-17 23:41:34
2020-01-17 23:41:36
2020-01-17 23:41:38
2020-01-17 23:41:40
方法二、用python線程(threading)的Timer模塊
import datetime
import threading
def do_job():
# threading.Timer(2,do_job,())
# 第一個參數: 延遲多長時間執行任務(單位: 秒)
# 第二個參數: 要執行的任務, 即函數
# 第三個參數: 調用函數的參數(tuple)
global timer
print(datetime.datetime.now().strftime("%H-%m-%d %H:%M:%S"))
timer = threading.Timer(2, do_job, ())
timer.start()
if __name__ == '__main__':
do_job()
輸出結果
00-01-18 00:06:14
00-01-18 00:06:16
00-01-18 00:06:18
00-01-18 00:06:20
00-01-18 00:06:22
00-01-18 00:06:24
網上有資料說這個方法要用 global 這個關鍵字,不使用的話會造成線程堆積,最終程序退出 ,經過測試這是沒有必要的。測試方法如下:
import datetime
import threading
def do_job(num):
# threading.Timer(2,do_job,())
# 第一個參數: 延遲多長時間執行任務(單位: 秒)
# 第二個參數: 要執行的任務, 即函數
# 第三個參數: 調用函數的參數(tuple)
# global timer
num += 1
print("do_job 執行的次數:", num)
print("當前線程數:{}".format(threading.active_count()))
print("\n")
if num > 4:
return
print(datetime.datetime.now().strftime("%H-%m-%d %H:%M:%S"))
timer = threading.Timer(2, do_job, (num,))
timer.start()
if __name__ == '__main__':
do_job(0)
輸出結果
do_job 執行的次數: 1
當前線程數:1
00-01-18 00:15:41
do_job 執行的次數: 2
當前線程數:2
00-01-18 00:15:43
do_job 執行的次數: 3
當前線程數:2
00-01-18 00:15:45
do_job 執行的次數: 4
當前線程數:2
00-01-18 00:15:47
do_job 執行的次數: 5
當前線程數:2
由此可以證明:不加global 當前活躍的線程數並沒有增加!因此global是沒有必要的
注:threading.active_count()是用來顯示當前活躍的進程數。
方法三、使用標準庫中sched模塊
sched 是事件調度器,通過 scheduler 類來調度事件,從而達到定時執行任務的效果,用法如下:
import sched
import time
# 生成調度器
scheduler = sched.scheduler(time.time, time.sleep)
def print_event(name):
print('EVENT:', time.time(), name)
print('START:', time.time())
# 分別設置在執行後2秒、3秒之後執行調用函數
scheduler.enter(2, 1, print_event, ('first',))
scheduler.enter(3, 1, print_event, ('second',))
# 運行調度器
scheduler.run()
輸出結果
START: 1579278724.9186893
EVENT: 1579278726.9192598 first
EVENT: 1579278727.920072 second
sched模塊是python標準時間調度器,後續會專門詳細講解用法。也可關注本人公衆號:DeepLearning大講堂