Python 執行緒模組中的 Timer 類

Vaibhav Vaibhav 2022年5月18日
Python 執行緒模組中的 Timer 類

執行緒是併發執行多個執行緒以實現並行性的技術。在 Python 中,我們可以使用 threading 模組來實現執行緒化。現在,threading 模組有一個 Timer 類,可用於在 x 時間後執行某些操作或執行某些程式碼。在本文中,我們將通過示例瞭解如何使用該類並更好地理解它。我們將構建一個無限計時器。

Python 中的 threading.Timer

Timer 類是 Thread 類的子類,可用於在一些時間單位後執行程式碼。它接受兩個引數,即 intervalfunctioninterval 是指程式碼應該執行的秒數,而 function 是在所需時間過去後應該呼叫的回撥函式。這個類有兩個重要的函式,即 start()cancel()start() 方法用於啟動計時器,cancel() 方法用於取消它。

計時器物件預設不啟動。我們必須呼叫 start() 方法來啟動它們。要停止正在執行的計時器,我們可以使用 cancel() 方法。

現在我們已經完成了理論,讓我們瞭解如何實際使用這個類來建立一個無限計時器。相同的參考下面的程式碼。

from time import sleep
from threading import Timer
from datetime import datetime


class MyInfiniteTimer:
    """
    A Thread that executes infinitely
    """

    def __init__(self, t, hFunction):
        self.t = t
        self.hFunction = hFunction
        self.thread = Timer(self.t, self.handle_function)

    def handle_function(self):
        self.hFunction()
        self.thread = Timer(self.t, self.handle_function)
        self.thread.start()

    def start(self):
        self.thread = Timer(self.t, self.handle_function)
        self.thread.start()

    def cancel(self):
        self.thread.cancel()


def print_current_datetime():
    print(datetime.today())


t = MyInfiniteTimer(1, print_current_datetime)
t.start()
sleep(5)
t.cancel()
sleep(5)
t.start()
sleep(5)
t.cancel()

輸出:

2021-10-31 05:51:20.754663
2021-10-31 05:51:21.755083
2021-10-31 05:51:22.755459
2021-10-31 05:51:23.755838
2021-10-31 05:51:24.756172
2021-10-31 05:51:30.764942
2021-10-31 05:51:31.765281
2021-10-31 05:51:32.765605
2021-10-31 05:51:33.766017
2021-10-31 05:51:34.766357

正如我們所見,MyInfiniteTimer 類使用了 Timer 類。它接受兩個引數:thFunction,它們指的是秒數和 Timer 物件的回撥函式。建立 MyInfiniteTimer 類物件時,該類的建構函式會建立一個新的計時器物件,但不會啟動它。可以使用 MyInfiniteTimer 類的 start() 方法啟動計時器。並使用 stop() 方法,可以停止計時器。當前計時器結束後,處理程式或 handle_function() 會建立一個與前一個計時器具有相同配置的新計時器並啟動它。

為了展示 MyInfiniteTimer 類的工作,我們首先在 29 行建立了一個新的 MyInfiniteTimer 類物件,然後呼叫了 start() 方法。接下來,我們等待 5 秒或讓計時器執行 5 秒。然後我們停止計時器並再次等待 5 秒。最後,我們重複最後兩個過程,然後程式終止。

作者: Vaibhav Vaibhav
Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

相關文章 - Python Threading