Python: 定時器(Timer)簡單實現


項目分析中發現有網站下載過程中需要發送心跳指令,復習下定時器,其與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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM