python執行定時任務__python

來源:互聯網
上載者:User

一,當你想讓你某個方法在幾秒甚至更長的時間內執行後執行一次,你可以這樣做:

import timefrom threading import Timerdef print_time( enter_time ):  print "now is", time.time() , "enter_the_box_time is", enter_timeprint time.time()Timer(5,  print_time, ( time.time(), )).start()Timer(10, print_time, ( time.time(), )).start()print time.time()

這樣的話,從程式開始執行到5,秒,10秒都會執行一次print_time這個方法。

二,當你想讓你的某個方法每個一定周期執行呢,這就需要定時任務的架構APScheduler,網上介紹安裝apscheduler的方法很簡單,就是:

easy_install apscheduler就行了,可惜我可能用的Python 2.7的原因,雖然有提示安裝成功,但是寫代碼引入這些包的時候總是出問題,最後

我找到了一個apscheduler2.0 的軟體包,解壓後切換至相應目錄後python setup.py install才把問題解決,這個軟體包在我的資源可以下載到。

然後你就可以開始寫代碼了,代碼實現風格有兩個:

1,帶修飾器的寫法:

from apscheduler.scheduler import Schedulerimport datetimeschedudler = Scheduler(daemonic = False)@schedudler.cron_schedule(second='15', day_of_week='0-7', hour='9-12,13-16')def quote_send_sh_job():    print 'a simple cron job start at', datetime.datetime.now()schedudler.start()

2,不帶修飾器的寫法:

def cornstart(self,event):         schedudler = Scheduler(daemonic = True)         schedudler.add_cron_job(self.timing_exe, day_of_week='mon-sun', hour='0-12', minute='0-59', second='15',)         print 'get start'         schedudler.start()

應該好理解,timing_exe是要執行的函數名,如果函數還有參數可以加一個args[]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.