Python threading.Timer 提供簡單的一次性定時執行。本文進一步封裝可重複使用的計時器類別支援倒數顯示、週期性執行與到期動作觸發。
基本 Timer 用法
import threading
def say_sth(s):
print s
t = threading.Timer(2.0, say_sth, ['i am here too.'])
t.start()
可擴充計時器類別體系
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=[]):
self.args = args
self.action = action
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()
類別對比
| 類別 | 功能 | 適用場景 |
threading.Timer | 一次性延遲執行 | 簡單排程、延遲重試 |
Timer | 繼承 Thread,可擴充 | 自訂計時邏輯基類 |
CountDownTimer | 倒數列印秒數 | UI 倒數、進度顯示 |
CountDownExec | 倒數結束觸發回調 | 定時任務、超時處理 |
進階擴充建議
- 週期性執行:
run() 中迴圈 + time.sleep(interval)
- 取消機制:
threading.Event 控制迴圈退出
- 參數傳遞:支援
*args, **kwargs
- 異常處理:
try/except 包裹回調避免執行緒崩潰
- 精確度:
time.monotonic() 計算下次喚醒時間
生產環境替代方案
| 庫/模組 | 特點 |
sched | 標準庫排程器,支援優先級、延遲、週期 |
APScheduler | 功能豐富:cron、interval、date 觸發器、持久化、分散式 |
celery beat | 分散式任務隊列定時任務 |
asyncio | Python 3.4+ 非同步排程 |