python 定時執行函數方法

來源:互聯網
上載者:User

 

一、Timer類基本介紹
這個類表示一個動作應該在一個特定的時間之後運行 — 也就是一個計時器。Timer是Thread的子類, 因此也可以使用函數建立自訂線程。
class threading.Timer(interval, function, args=[], kwargs={}) 
建立一個timer,在interval秒過去之後,它將以參數args和關鍵字參數kwargs運行function 。

 

二、簡單例子 # coding: utf-8 from threading import Timer def fun():     print "hello, world" if __name__=='__main__':     t = Timer(5.0, fun)     t.start() # 5秒後, "hello, world"將被列印

三、取消線程執行Timers通過調用它們的start()方法作為線程啟動。timer可以通過調用cancel()方法(在它的動作開始之前)停止。timer在執行它的動作之前等待的時間間隔可能與使用者指定的時間間隔不完全相同。cancel() 停止timer,並取消timer動作的執行。這隻在timer仍然處於等待階段時才工作。
# coding: utf-8from threading import Timerdef fun():    print "hello, world"if __name__=='__main__':    t = Timer(5.0, fun)    t.start() # 開始執行線程,但是不會列印"hello, world"    t.cancel() # 因為cancel取消了線程的執行,所以fun()函數不會被執行



















聯繫我們

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