首頁 後端開發 Python教學 python實作循環定時器的方法介紹(附程式碼)

python實作循環定時器的方法介紹(附程式碼)

Mar 14, 2019 am 11:13 AM
python

這篇文章帶給大家的內容是關於python實現循環定時器的方法介紹(附程式碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

python 如何寫一個定時器,循環定時要做某一操作呢?

Timer 物件

from threading import Timer
def hello(): 
    print "hello, world" 
   
t = Timer(10.0, hello) 
t.start()
登入後複製

10秒後輸出:

hello, world
登入後複製

重點研究 t = Timer(10.0, hello) 這句程式碼,python 提供了一個Timer 對象,它會在指定的時間後執行某一操作;它的完整形式:

class threading.Timer(interval, function, args=[], kwargs={})
登入後複製

interval 是時間間隔,function 是可呼叫的對象,args 和 kwargs 會作為 function 的參數。

注意:這裡只會執行一次 function,而不會一直定時執行,且 Timer 在執行操作的時候會建立一個新的執行緒。

Timer 在 python2 和 python3 有點區別:

# python2.7
def Timer(*args, **kwargs):
    return _Timer(*args, **kwargs)
# python3.7
class Timer(Thread):
    pass
登入後複製

在 python3,Timer 是 Thread 的子類別;在 python2,_Timer 是 Thread 的子類,而Tim 只是工廠類型的方法Tim _Thread 的子類,而Tim 只是工廠的方法。

上面的程式碼只會列印一次 hello, world 後退出,那麼如何循環間隔列印呢?

粗糙的循環計時器

一種方法是在 function 裡繼續註冊一個Timer,這樣就可以在下一個 interval 繼續執行 function;

from threading import Timer
def hello(): 
    print "hello, world" 
    Timer(10.0, hello) .start()

t = Timer(10.0, hello) 
t.start()
登入後複製

每隔10 秒

每隔10 秒

每隔10 秒
每隔10 秒輸出一個 hello, world。

達到效果了,但這裡面好像有點問題。回到 Timer 本身,它是一個 thread,每次循環間隔操作,系統都要創建一個線程,然後再回收,這對系統來說開銷很大。如果時間間隔 interval 很短,系統會一下子創建很多線程,這些線程很難快速回收,導致系統記憶體和cpu資源被消耗掉。

所以不主張在 function 裡繼續註冊一個 Timer。

更pythonic 循環定時器

這裡有更pythonic 的方法:

from threading import _Timer
def hello():
     print "hello, world"
class RepeatingTimer(_Timer): 
    def run(self):
        while not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
            self.finished.wait(self.interval)
t = RepeatingTimer(10.0, hello)
t.start()
登入後複製
重點研究 RepeatingTimer 類,它繼承了 threading._Timer,但是重寫了父類的run 方法。這是 Python2 的寫法,python3 中 RepeatingTimer 應該要繼承 threading.Timer。

為什麼要重寫 Thread 的 run 方法?

_Timer 是個 Thread 子類,我們先來看看 Thread 類別的 run 用法。

from threading import Thread
def hello():
     print "hello, world"
# 继承 Thread
class MyThread(Thread):
    # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
    def run(self):
        hello()
t = MyThread()
t.start()
登入後複製
Thread 物件的完整定義:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
登入後複製
其中 run 方法程式碼:

class Thread(_Verbose):
    def run(self):
        try:
            if self.__target:
                self.__target(*self.__args, **self.__kwargs)
        finally:
            # Avoid a refcycle if the thread is running a function with
            # an argument that has a member that points to the thread.
            del self.__target, self.__args, self.__kwargs
登入後複製
標準的 run 方法用於執行使用者傳入建構函數的 target 方法。子類別可以重寫 run 方法,把要執行的程式碼寫到 run 裡面,執行緒在建立後,使用者呼叫 start() 方法會執行 run() 方法。

所以 RepeatingTimer 重寫 _Timer 的 run() 方法,可以改變執行緒的執行體,當我們呼叫 RepeatingTimer 的 start() 方法時會執行我們重寫的 run() 方法。

再看看 RepeatingTimer 類別中的 while not self.finished.is_set() 語句,self.finished.is_set() 直到 True 才會退出循環,計時器才會退出。 finished 是 threading.Event 物件。一個 Event 物件管理一個flag 標誌,它能被 set() 方法設定為True,也能被 clear() 方法設定為False,呼叫 wait([timeout]) 執行緒會一直sleep 到flag 為True 或逾時時間到達。

我們知道計時器有一個 cancel() 方法可以提前取消操作。它其實是呼叫 Event.clear() 方法提前讓 wait 方法結束等待,並且判斷在 flag 為 true 的情況下不執行定時器操作。特定的程式碼:###
class _Timer(Thread):
    """Call a function after a specified number of seconds:
            t = Timer(30.0, f, args=[], kwargs={})
            t.start()
            t.cancel() # stop the timer's action if it's still waiting
    """

    def __init__(self, interval, function, args=[], kwargs={}):
        Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.finished = Event()

    def cancel(self):
        """Stop the timer if it hasn't finished yet"""
        self.finished.set()

    def run(self):
        self.finished.wait(self.interval)
        if not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
        self.finished.set()
登入後複製
###所以 RepeatingTimer 的 run 方法會一直執行 while 循環體,在循環體了會執行使用者傳入的 function 對象,並等待指定的時間。當使用者想要退出計時器時,只要呼叫 cancel 方法,將 flag 置為 True 便不會繼續執行循環體了。這樣便完成了一個還不錯的循環定時器。 ###

以上是python實作循環定時器的方法介紹(附程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

PHP和Python:解釋了不同的範例 PHP和Python:解釋了不同的範例 Apr 18, 2025 am 12:26 AM

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

在PHP和Python之間進行選擇:指南 在PHP和Python之間進行選擇:指南 Apr 18, 2025 am 12:24 AM

PHP適合網頁開發和快速原型開發,Python適用於數據科學和機器學習。 1.PHP用於動態網頁開發,語法簡單,適合快速開發。 2.Python語法簡潔,適用於多領域,庫生態系統強大。

Python vs. JavaScript:學習曲線和易用性 Python vs. JavaScript:學習曲線和易用性 Apr 16, 2025 am 12:12 AM

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

PHP和Python:深入了解他們的歷史 PHP和Python:深入了解他們的歷史 Apr 18, 2025 am 12:25 AM

PHP起源於1994年,由RasmusLerdorf開發,最初用於跟踪網站訪問者,逐漸演變為服務器端腳本語言,廣泛應用於網頁開發。 Python由GuidovanRossum於1980年代末開發,1991年首次發布,強調代碼可讀性和簡潔性,適用於科學計算、數據分析等領域。

vs code 可以在 Windows 8 中運行嗎 vs code 可以在 Windows 8 中運行嗎 Apr 15, 2025 pm 07:24 PM

VS Code可以在Windows 8上運行,但體驗可能不佳。首先確保系統已更新到最新補丁,然後下載與系統架構匹配的VS Code安裝包,按照提示安裝。安裝後,注意某些擴展程序可能與Windows 8不兼容,需要尋找替代擴展或在虛擬機中使用更新的Windows系統。安裝必要的擴展,檢查是否正常工作。儘管VS Code在Windows 8上可行,但建議升級到更新的Windows系統以獲得更好的開發體驗和安全保障。

visual studio code 可以用於 python 嗎 visual studio code 可以用於 python 嗎 Apr 15, 2025 pm 08:18 PM

VS Code 可用於編寫 Python,並提供許多功能,使其成為開發 Python 應用程序的理想工具。它允許用戶:安裝 Python 擴展,以獲得代碼補全、語法高亮和調試等功能。使用調試器逐步跟踪代碼,查找和修復錯誤。集成 Git,進行版本控制。使用代碼格式化工具,保持代碼一致性。使用 Linting 工具,提前發現潛在問題。

notepad 怎麼運行python notepad 怎麼運行python Apr 16, 2025 pm 07:33 PM

在 Notepad 中運行 Python 代碼需要安裝 Python 可執行文件和 NppExec 插件。安裝 Python 並為其添加 PATH 後,在 NppExec 插件中配置命令為“python”、參數為“{CURRENT_DIRECTORY}{FILE_NAME}”,即可在 Notepad 中通過快捷鍵“F6”運行 Python 代碼。

vscode 擴展是否是惡意的 vscode 擴展是否是惡意的 Apr 15, 2025 pm 07:57 PM

VS Code 擴展存在惡意風險,例如隱藏惡意代碼、利用漏洞、偽裝成合法擴展。識別惡意擴展的方法包括:檢查發布者、閱讀評論、檢查代碼、謹慎安裝。安全措施還包括:安全意識、良好習慣、定期更新和殺毒軟件。

See all articles