调度 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 - 首次调度的日期/时间
  • end_date - 可选,停止新实例的时间
    • start_dateend_date 均使用 datetime(year, month, day) 对象,例如:
       from pendulum import datetime
       start_date=datetime(2026, 4, 10, tz="UTC")
      
Python 中的 Apache Airflow 入门

Schedule

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 - 从不调度,用于手动触发的 Dag
  • @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 日

Python 中的 Apache Airflow 入门

让我们来练习!

Python 中的 Apache Airflow 入门

Preparing Video For Download...