python定時任務-sched模組

來源:互聯網
上載者:User

標籤:spi   過多   對象   thread   設定   threading   簡單   run   浮點數   

通過sched模組可以實現通過自訂時間,自訂函數,自訂優先順序來執行函數。範例一
 1 import time 2 import sched 3  4 schedule = sched.scheduler( time.time,time.sleep) 5  6 def func(string1): 7     print "now excuted func is %s"%string1 8  9 print "start"10 schedule.enter(2,0,func,(1,))11 schedule.enter(2,0,func,(2,))12 schedule.enter(3,0,func,(3,))13 schedule.enter(4,0,func,(4,))14 schedule.run()15 16 print "end"
schedule是一個對象,叫什麼名字都可以schedule.enter(delay,priority,action,arguments)第一個參數是一個整數或浮點數,代表多少秒後執行這個action任務第二個參數priority是優先順序,0代表優先順序最高,1次之,2次次之,當兩個任務是預定在同一個時刻執行時,根據優先順序決定誰先執行。第三個參數就是你要執行的任務,可以簡單理解成你要執行任務的函數的函數名第四個參數是你要傳入這個定時執行函數名函數的參數,最好用括弧包起來,如果只傳入一個參數的時候用括弧包起來,該參數後面一定要加一個逗號,如果不打逗號,會出現錯誤。例如schedule.enter(delay, priority, action, (argument1,)) run()一直被阻塞,直到所有任務全部執行結束。每個任務在同一線程中運行,所以如果一個任務執行時間大於其他任務的等待時間,那麼其他任務會延遲任務的執行時間,這樣保證沒有任務丟失,但這些任務的調用時間會比設定的延遲。 多線程執行定時任務範例二
1 import time2 import sched3 from threading import Timer4 def print_name(str):5     print "i‘m %s"%str6 print "start"7 Timer(5,print_name,("superman",)).start()8 Timer(10,print_name,("spiderman",)).start()9 print "end"
通過多線程,實現定時任務在多線程中,如果只通過schedule,會因為安全執行緒的問題會出現阻塞,一個任務執行,如果沒有結束而另一個任務就要等待。通過threading.Timer可以避免這個問題效果就是直接執行Print start和print end,而定時任務會分開執行。列印end不會阻塞。  

python定時任務-sched模組

聯繫我們

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