Python定時任務__Python

來源:互聯網
上載者:User

Python下實現定時任務的方式有很多種方式。


迴圈sleep:

這是一種最簡單的方式,在迴圈裡放入要執行的任務,然後sleep一段時間再執行。缺點是,不容易控制,而且sleep是個阻塞函數。

def timer(n):    '''    每n秒執行一次    '''    while True:          print time.strftime('%Y-%m-%d %X',time.localtime())          yourTask()  # 此處為要執行的任務          time.sleep(n) 


threading的Timer:

threading模組中的Timer能夠協助實現定時任務,而且是非阻塞的。

比如3秒後列印helloworld:

def printHello():    print "hello world"Timer(3, printHello).start()

比如每3秒列印一次helloworld:

def printHello():    print "Hello World"    t = Timer(2, printHello)    t.start()if __name__ == "__main__":    printHello()

 

使用sched模組:

sched是一種調度(延時處理機制)。

# -*- coding:utf-8 -*-# use sched to timingimport timeimport osimport sched# 初始化sched模組的scheduler類# 第一個參數是一個可以返回時間戳記的函數,第二個參數可以在定時未到達之前阻塞。schedule = sched.scheduler(time.time, time.sleep)# 被周期性調度觸發的函數def execute_command(cmd, inc):    '''    終端上顯示當前電腦的串連情況    '''    os.system(cmd)    schedule.enter(inc, 0, execute_command, (cmd, inc))def main(cmd, inc=60):    # enter四個參數分別為:間隔事件、優先順序(用於同時間到達的兩個事件同時執行時定序)、被調用觸發的函數,    # 給該觸發函數的參數(tuple形式)    schedule.enter(0, 0, execute_command, (cmd, inc))    schedule.run()# 每60秒查看下網路連接情況if __name__ == '__main__':    main("netstat -an", 60)


使用定時架構APScheduler:

APScheduler是基於Quartz的一個Python定時任務架構。提供了基於日期、固定時間間隔以及crontab類型的任務,並且可以持久化任務。

這個現在還沒自己嘗試過,等過段時間用了再來補充。


使用windows的定時任務:

這裡可以將所需要的Python程式打包成exe檔案,然後在windows下設定定時執行。


使用Linux的定時任務(Crontab):

在Linux下可以很方便的藉助Crontab來設定和運行定時任務。進入Crontab檔案編輯頁面,設定時間間隔,使用一些shell命令來運行bash指令碼或者是Python指令碼,儲存後Linux會自動按照設定的時間來定時運行程式。



聯繫我們

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