首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python threading.Timer 與自訂倒數計時器類別實現:一次性、週期性與動作觸發

     編輯:更多程式設計知識

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分散式任務隊列定時任務
asyncioPython 3.4+ 非同步排程
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved