python 定時器每天就執(zhí)行一次的實現(xiàn)代碼
1.實現(xiàn)功能
編寫python腳本一直運行,判斷當下是否是新的一天,如果是就執(zhí)行一次任務代碼
2.具體實現(xiàn)代碼
#-*-coding:utf-8 -*- __author__ = 'Administrator' import os,threading,time curTime=time.strftime("%Y-%M-%D",time.localtime())#記錄當前時間 execF=False ncount=0 def execTask(): #具體任務執(zhí)行內(nèi)容 print("execTask executed!") def timerTask(): global execF global curTime global ncount if execF is False: execTask()#判斷任務是否執(zhí)行過,沒有執(zhí)行就執(zhí)行 execF=True else:#任務執(zhí)行過,判斷時間是否新的一天。如果是就執(zhí)行任務 desTime=time.strftime("%Y-%M-%D",time.localtime()) if desTime > curTime: execF = False#任務執(zhí)行執(zhí)行置值為 curTime=desTime ncount = ncount+1 timer = threading.Timer(5,timerTask) timer.start() print("定時器執(zhí)行%d次"%(ncount)) if __name__=="__main__": timer = threading.Timer(5,timerTask) timer.start()
使用Python 執(zhí)行具體任務執(zhí)行
知識點擴展:
Python: 定時器(Timer)簡單實現(xiàn)
項目分析中發(fā)現(xiàn)有網(wǎng)站下載過程中需要發(fā)送心跳指令,復習下定時器,其與javascript中實現(xiàn)方法類似。
其原理為執(zhí)行函數(shù)中置定時函數(shù)Timer(),遞歸調(diào)用自己,看來實現(xiàn)方法比較拙劣。
假定1秒觸發(fā)一次,并置結(jié)束條件為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
總結(jié)
以上所述是小編給大家介紹的python 定時器每天就執(zhí)行一次的實現(xiàn)代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關文章
Pytorch用Tensorboard來觀察數(shù)據(jù)
這篇文章主要介紹了Pytorch用Tensorboard來觀察數(shù)據(jù),上一篇文章我們講解了關于Pytorch?Dataset的數(shù)據(jù)處理,這篇我們就來講解觀察數(shù)據(jù),下面具體相關資料,需要的朋友可以參考一下,希望對你有所幫助2021-12-12Windows系統(tǒng)配置python腳本開機啟動的3種方法分享
這篇文章主要介紹了Windows系統(tǒng)配置python腳本開機啟動的3種方法分享,本文講解了開始菜單啟動項實現(xiàn)、開機腳本、通過一個服務調(diào)用該腳本三種方法,需要的朋友可以參考下2015-03-03如何使用Typora+MinIO+Python代碼打造舒適協(xié)作環(huán)境
這篇文章主要介紹了如何使用Typora+MinIO+Python代碼打造舒適協(xié)作環(huán)境,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-05-05