python定時執行方法

來源:互聯網
上載者:User

標籤:缺點   任務   sleep   pytho   ring   表示   threading   線程   非阻塞   

1  time.sleep

import time

for i in range(5):

  print(i)

  time.sleep(10)

2 用shed

import time  import sched    schedule = sched.scheduler ( time.time, time.sleep )    def func(string1,float1):      print("now is",time.time()," | output=",string1,float1)  print(time.time())schedule.enter(2,0,func,("test1",time.time()))  schedule.enter(2,0,func,("test1",time.time()))  schedule.enter(3,0,func,("test1",time.time()))  schedule.enter(4,0,func,("test1",time.time()))  schedule.run()  print(time.time())

其中func中放要執行的函數,用schedule.enter加入要執行的函數,裡面的第一個參數是順延強制的時間,用sched.scheduler進行初始化

1512033155.9311035now is 1512033157.9316308  | output= test1 1512033155.9311035now is 1512033157.9316308  | output= test1 1512033155.9311035now is 1512033158.9322016  | output= test1 1512033155.9311035now is 1512033159.9316351  | output= test1 1512033155.93110351512033159.9316351[Finished in 4.2s]

上面是執行結果,缺點是任務隊列是阻塞型,即schedule裡的任務不執行完,後面的主線程就不會執行

3  用threading裡的timer,實現非阻塞型,即主線程要任務同時執行

import time  from threading import Timer    def print_time( enter_time ):      print "now is", time.time() , "enter_the_box_time is", enter_time      print time.time()  Timer(5,  print_time, ( time.time(), )).start()  Timer(10, print_time, ( time.time(), )).start()  print time.time()  

執行結果:

1512034286.94431691512034286.9452875now is 1512034291.9460146 enter_the_box_time is 1512034286.9443169now is 1512034296.9461012 enter_the_box_time is 1512034286.9452875[Finished in 10.2s]

可看出任務和主線程是同步執行,但是後3位又稍有不同,應該是python的多線程並非真正的多線程導致

每天某個時間定時執行任務:

import datetimeimport timedef doSth():    print(‘test‘)    # 假裝做這件事情需要一分鐘    time.sleep(60)def main(h=0, m=0):    ‘‘‘h表示設定的小時,m為設定的分鐘‘‘‘    while True:        # 判斷是否達到設定時間,例如0:00        while True:            now = datetime.datetime.now()            # 到達設定時間,結束內迴圈            if now.hour==h and now.minute==m:                break            # 不到時間就等20秒之後再次檢測            time.sleep(20)        # 做正事,一天做一次        doSth()main()

 

python定時執行方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.