萬盛學電腦網

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

Python 任務排程實戰:sched、threading.Timer、APScheduler 三種方案比較

前言

Python 內建 sched 與 threading.Timer 可處理簡單排程,但生產環境建議使用功能完善的 APScheduler。本文對比三種方案,並提供實用範本。

方案一:sched.scheduler (標準庫,單執行緒阻塞)

import sched, time, datetime

s = sched.scheduler(time.time, time.sleep)

def job(name):
    print(f'[{datetime.datetime.now()}] 執行 {name}')

# 絕對時間排程 (5 秒後)
run_at = time.time() + 5
s.enterabs(run_at, 1, job, ('任務A',))

# 相對時間循環 (每 3 秒)
def periodic():
    job('週期任務')
    s.enter(3, 1, periodic)
s.enter(3, 1, periodic)

print('排程器啟動... (Ctrl+C 停止)')
try:
    s.run(blocking=True)
except KeyboardInterrupt:
    print('已停止')

缺點:run() 會阻塞主執行緒;無持久化、無錯誤重試、無分散式支援。

方案二:threading.Timer (非阻塞,適合一次性延遲)

import threading, time, datetime

def delayed_job(msg, delay):
    def _run():
        print(f'[{datetime.datetime.now()}] {msg}')
    t = threading.Timer(delay, _run)
    t.daemon = True  # 主程式結束時自動結束
    t.start()
    return t

# 5 秒後執行一次
delayed_job('延遲任務', 5)

# 週期性執行需自行遞迴
def periodic_job(interval):
    def _run():
        print(f'[{datetime.datetime.now()}] 週期執行')
        threading.Timer(interval, _run).start()
    _run()

periodic_job(3)
# 主執行緒可繼續做其他事
time.sleep(20)

缺點:長時間運行會累積時間誤差;無管理介面、無持久化、例外處理困難。

方案三:APScheduler (生產級排程框架)

安裝

pip install apscheduler

核心概念

  • Trigger:date (一次)、interval (固定間隔)、cron (類 crontab)。
  • Job Store:預設 MemoryJobStore;生產環境用 SQLAlchemyJobStore (資料庫) 持久化。
  • Executor:ThreadPoolExecutor (預設)、ProcessPoolExecutor (CPU 密集)。

完整範例:Web 服務背景任務

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
import logging, datetime, atexit

# 設定日誌
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 排程器配置
jobstores = {
    'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')
}
executors = {
    'default': ThreadPoolExecutor(20),
    'processpool': ProcessPoolExecutor(5)
}
job_defaults = {
    'coalesce': True,        # 積壓任務合併執行一次
    'max_instances': 3,      # 同一任務最多並行實例數
    'misfire_grace_time': 30 # 允許誤差秒數
}

scheduler = BackgroundScheduler(
    jobstores=jobstores,
    executors=executors,
    job_defaults=job_defaults,
    timezone='Asia/Taipei'
)

# 定義任務
def cleanup_temp_files():
    logger.info('清理暫存檔...')
    # 實際刪除邏輯
    pass

def send_daily_report():
    logger.info('發送每日報表...')
    # 郵件發送邏輯
    pass

def check_service_health():
    logger.info('健康檢查...')
    # API 呼叫檢查
    pass

# 新增任務
scheduler.add_job(cleanup_temp_files, 'interval', minutes=30, id='cleanup')
scheduler.add_job(send_daily_report, 'cron', hour=8, minute=0, id='daily_report')
scheduler.add_job(check_service_health, 'interval', minutes=5, id='health_check')

# 一次性任務
run_date = datetime.datetime.now() + datetime.timedelta(hours=1)
scheduler.add_job(lambda: print('1小時後執行'), 'date', run_date=run_date)

# 啟動
scheduler.start()
atexit.register(lambda: scheduler.shutdown(wait=False))

print('排程器已在背景執行...')
# 主程式繼續 (如 Flask/FastAPI app.run())
import time
try:
    while True:
        time.sleep(60)
except KeyboardInterrupt:
    scheduler.shutdown()

進階功能亮點

  • 動態增刪改查:scheduler.add_job(), remove_job(), modify_job(), get_jobs()。
  • 事件監聽:scheduler.add_listener(listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR) 可做失敗告警。
  • 分散式部署:共用資料庫 JobStore + 分散式鎖 (如 Redis Redlock) 避免重複執行。
  • Web 管理介面:搭配 apscheduler.web 或自建 API 查看任務狀態。

選型建議表

需求推薦方案
腳本內簡單延遲/單次任務threading.Timer / time.sleep
單一程序、少量週期任務、無持久化需求sched 或 APScheduler (MemoryJobStore)
需持久化、重啟後恢復、Cron 表達式、並發控制APScheduler + SQLAlchemyJobStore
分散式叢集、高可用、多節點去重APScheduler + Redis/DB 鎖 或 Celery Beat + Celery
Kubernetes 環境CronJob 資源物件

最佳實務提醒

  1. 任務函式務必捕獲例外,避免導致排程器執行緒崩潰。
  2. 長時間任務使用 processpool 執行器,避免阻塞其他任務。
  3. 設定 misfire_grace_time 防止系統忙碌時任務積壓。
  4. 生產環境啟用日誌記錄任務執行時間、結果、錯誤堆疊。
  5. 定期清理 jobs.sqlite 歷史記錄,避免檔案膨脹。
copyright © 萬盛學電腦網 all rights reserved