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']
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 封裝威力。