項目分析中發現有網站下載過程中需要發送心跳指令,復習下定時器,其與javascript中實現方法類似。
其原理為執行函數中置定時函數Timer(),遞歸調用自己,看來實現方法比較拙劣。
假定1秒觸發一次,並置結束條件為15秒:
import threading import time exec_count = 0 def heart_beat(): print time.strftime('%Y-%m-%d %H:%M:%S') global exec_count exec_count += 1
# 15秒后停止定時器 if exec_count < 15: threading.Timer(1, heart_beat).start() heart_beat()
另一種判斷方式:
import threading import time cancel_tmr = False def heart_beat(): print time.strftime('%Y-%m-%d %H:%M:%S')
if not cancel_tmr: threading.Timer(1, heart_beat).start() heart_beat()
# 15秒后停止定時器 time.sleep(15) cancel_tmr = True