python 一次性定时器_python 定时器每天就执行一次的实现代码
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 定時器每天就執行一次的實現代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對谷谷點程序網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
總結
以上是生活随笔為你收集整理的python 一次性定时器_python 定时器每天就执行一次的实现代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js 函数参数
- 下一篇: 包装类java_java中的包装类