python每天定时9点执行_python 定时器每天就执行一次的实现代码
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)載,煩請注明出處,謝謝!
總結(jié)
以上是生活随笔為你收集整理的python每天定时9点执行_python 定时器每天就执行一次的实现代码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大马女神出演Xbox Series S广
- 下一篇: python选择题题目_Python接口