萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python threading.Timer 實現定時器:從簡單調用到可復用類層次設計

Python threading.Timer 提供一次性延遲執行功能。本文從最簡單調用開始,逐步構建可倒計時、可執行動作的定時器類體系,展示面向對象封裝思想。

最簡單用法:一次性延遲執行

import threading

def say_sth(s):
    print(s)

t = threading.Timer(2.0, say_sth, ["hello"])
t.start()  # 2 秒後打印 "hello"

# 主線程不阻塞,程序不會退出,直到所有非守護線程結束

進階:定時器類層次

import threading
import time

class Timer(threading.Thread):
    """基礎定時器:睡眠指定秒數後打印提示"""
    def __init__(self, seconds):
        self.runTime = seconds
        threading.Thread.__init__(self)

    def run(self):
        time.sleep(self.runTime)
        print("Buzzzz!! Time's up!")

class CountDownTimer(Timer):
    """倒計時定時器:每秒打印剩餘秒數"""
    def run(self):
        counter = self.runTime
        for sec in range(self.runTime):
            print(counter)
            time.sleep(1.0)
            counter -= 1
        print("Done")

class CountDownExec(CountDownTimer):
    """倒計時結束執行動作"""
    def __init__(self, seconds, action, args=None):
        self.action = action
        self.args = args or []
        CountDownTimer.__init__(self, seconds)

    def run(self):
        CountDownTimer.run(self)
        self.action(self.args)

# 業務動作
def myAction(args):
    print("Performing my action with args:")
    print(args)

if __name__ == "__main__":
    t = CountDownExec(3, myAction, ["hello", "world"])
    t.start()
    # 主線程可繼續做其他事
    print("Main thread continues...")

運行輸出

Main thread continues...
3
2
1
Done
Performing my action with args:
['hello', 'world']

關鍵設計點

  • 繼承 threading.Thread:複用線程生命周期管理,start() 啟動異步執行。
  • 模板方法模式:CountDownExec.run 調用父類 run 完成倒計時,再執行動作,擴展性強。
  • 參數傳遞:args 列表傳給動作函數,支持任意可調用對象(函數、可調用對象、lambda)。

生產環境增強建議

  • 周期性定時器:while not self._stopped: time.sleep(interval); action() 模式。
  • 取消機制:threading.Event 控制循環退出,timer.cancel() 設置事件。
  • 異常捕獲:run 內包裹 try/except,避免線程靜默死亡。
  • 守護線程:self.daemon = True 讓主程序退出時自動結束定時器。
  • 高精度/大量定時器:考慮 sched 模塊、APScheduler、asyncio (Py3.4+)。

從 Timer(2, f) 到完整類體系,見證 Python 靈活的線程模型與 OOP 封裝威力。

copyright © 萬盛學電腦網 all rights reserved