1.實現功能
編寫python腳本一直運行,判斷當下是否是新的一天,如果是就執行一次任務代碼
2.具體實現代碼
#-*-coding:utf-8 -*-
__author__ = 'Administrator'
import os,threading,time
curTime=time.strftime("%Y-%M-%D",time.localtime())#記錄當前時間
execF=False
ncount=0
def execTask():
#具體任務執行內容
print("execTask executed!")
def timerTask():
global execF
global curTime
global ncount
if execF is False:
execTask()#判斷任務是否執行過,沒有執行就執行
execF=True
else:#任務執行過,判斷時間是否新的一天。如果是就執行任務
desTime=time.strftime("%Y-%M-%D",time.localtime())
if desTime > curTime:
execF = False#任務執行執行置值為
curTime=desTime
ncount = ncount+1
timer = threading.Timer(5,timerTask)
timer.start()
print("定時器執行%d次"%(ncount))
if __name__=="__main__":
timer = threading.Timer(5,timerTask)
timer.start()
使用Python 執行具體任務執行
知識點擴展:
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
總結
以上所述是小編給大家介紹的python 定時器每天就執行一次的實現代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

