排程 Dags

Python 中的 Apache Airflow 入門

Mike Metzger

Data Engineer

Dag 執行

  • 在某個時間點的特定工作流程執行個體
  • 可手動或透過 schedule 執行
  • 為每個工作流程與其中任務維護狀態
    • running
    • failed
    • success
1 https://airflow.apache.org/docs/stable/scheduler.html
Python 中的 Apache Airflow 入門

Dag 執行檢視

Airflow Dag Runs 頁面,列出所有 Dag 的近期執行

Python 中的 Apache Airflow 入門

Dag 執行狀態

Airflow Dag Runs 頁面顯示每次執行的狀態欄位

Python 中的 Apache Airflow 入門

排程細節

在為 Dag 設定排程時,有幾個重要屬性:

  • start_date:初次排程 Dag 執行的日期/時間
  • end_date:可選,用來停止建立新的 Dag 執行個體
    • start_dateend_date 都使用 datetime(year, month, day) 物件,例如:
       from pendulum import datetime
       start_date=datetime(2026, 4, 10, tz="UTC")
      
Python 中的 Apache Airflow 入門

排程

schedule 表示:

  • Dag 的排程頻率
  • 介於 start_dateend_date 之間
  • 可用 cron 語法、內建預設或 timedelta 定義。
Python 中的 Apache Airflow 入門

cron 語法

cron 語法示意圖,顯示以空白分隔的五個時間欄位

  • 來自 Unix 的 cron 格式
  • 以空白分隔的 5 個欄位
  • * 代表每個區間都執行(如每分鐘、每天)
  • 欄位可用逗號分隔列出多個值
Python 中的 Apache Airflow 入門

cron 範例

cron 語法示意圖,顯示以空白分隔的五個時間欄位

0 12 * * *              # 每天中午執行
* * 25 2 *              # 2 月 25 日每分鐘執行一次
0,15,30,45 * * * *      # 每 15 分鐘執行
Python 中的 Apache Airflow 入門

Airflow 排程預設

預設值:

  • @hourly
  • @daily
  • @weekly
  • @monthly
  • @yearly

對應的 cron:

  • 0 * * * *
  • 0 0 * * *
  • 0 0 * * 0
  • 0 0 1 * *
  • 0 0 1 1 *
1 https://airflow.apache.org/docs/stable/scheduler.html
Python 中的 Apache Airflow 入門

特殊預設

Airflow 有三個特殊的 schedule 預設:

  • None:永不排程,用於手動觸發的 Dags
  • @once:只排程一次
  • @continuous:前一次完成後立刻執行
Python 中的 Apache Airflow 入門

timedelta

  • 也可使用 pendulum.duration
  • duration(hours=6)
  • duration(minutes=30)
from pendulum import duration

@dag(
  dag_id="example_dag"
  schedule=duration(days=2)
)
Python 中的 Apache Airflow 入門

套用排程

  • 在 Dag 上定義排程
  • 使用 schedule 參數:
@dag(
  dag_id="example_dag",
  schedule="0 12 * * *"
)
@dag(
  dag_id="example_dag",
  schedule="@daily"     
)
Python 中的 Apache Airflow 入門

排程注意事項

當為 Dag 設定排程時,Airflow 會:

  • 必須在開始日期之後經過完整一個區間
  • 將任務排在 start_date + schedule
'start_date': datetime(2026, 2, 25, tz="UTC")
'schedule': @daily

最早可於 2026 年 2 月 26 日開始執行該 Dag

Python 中的 Apache Airflow 入門

一起來練習吧!

Python 中的 Apache Airflow 入門

Preparing Video For Download...