Airflow中的执行顺序

时间:2018-06-11 13:45:13

标签: python airflow

我正在审核示例代码here

有两个"操作"功能:

def my_sleeping_function(random_base):
    """This is a function that will run within the DAG execution"""
    time.sleep(random_base)

def print_context(ds, **kwargs):
    pprint(kwargs)
    print(ds)
    return 'Whatever you return gets printed in the logs'

对于my_sleeping_function的每次运行,我们都会运行print_context

我不明白的是订单。 这是图表和树...执行顺序不相同:

enter image description here enter image description here

先发生什么?之后发生了什么?为什么呢?

我认为根据这个:

for i in range(5):
    task = PythonOperator(
        task_id='sleep_for_' + str(i),
        python_callable=my_sleeping_function,
        op_kwargs={'random_base': float(i) / 10},
        dag=dag)

    task.set_upstream(run_this)

run_this执行然后执行任务,但循环让我困惑。

3 个答案:

答案 0 :(得分:3)

我认为您的困惑是基于您期望图表视图和树视图是两个单独的可视化同一事物。然而,它们被用于可视化不同的事物。

图表视图显示了任务在工作流程中的运行顺序。在您的情况下,print_the_context将会运行,一旦完成sleep_for_0sleep_for_1sleep_for_2sleep_for_3sleep_for_4将会并行运行(或至少与气流配置允许的平行)

树视图表示DAG的深度优先可视化(以及右侧方块中每个任务随时间的状态)。也就是说树中的第一级节点是dag(叶节点)中的最终任务,其中dag将被认为是成功完成的。它为每个必须运行的依赖任务分支出来。

换句话说,两个视图中的执行顺序是相同的,只是从不同的方向可视化。

答案 1 :(得分:1)

这里的循环只是向您展示如何动态构建DAG。事物执行的顺序取决于您设置为“上游”或“下游”任务的顺序。

您链接到的示例也可以像下面的示例一样完成。但是,如果你想添加另外10个任务怎么办?你必须做很多复制/粘贴编码来实现同样的目的,最好只是把它放在一个循环中,就像在链接的例子中一样:

def my_sleeping_function(random_base):
    """This is a function that will run within the DAG execution"""
    time.sleep(random_base)


def print_context(ds, **kwargs):
    pprint(kwargs)
    print(ds)
    return 'Whatever you return gets printed in the logs'


run_this = PythonOperator(
    task_id='print_the_context',
    provide_context=True,
    python_callable=print_context,
    dag=dag)

task_0 = PythonOperator(
    task_id='sleep_for_' + 0,
    python_callable=my_sleeping_function,
    op_kwargs={'random_base': float(0) / 10},
    dag=dag)

task_1 = PythonOperator(
    task_id='sleep_for_' + 1,
    python_callable=my_sleeping_function,
    op_kwargs={'random_base': float(1) / 10},
    dag=dag)

task_2 = PythonOperator(
    task_id='sleep_for_' + 2,
    python_callable=my_sleeping_function,
    op_kwargs={'random_base': float(2) / 10},
    dag=dag)


task_3 = PythonOperator(
    task_id='sleep_for_' + 3,
    python_callable=my_sleeping_function,
    op_kwargs={'random_base': float(3) / 10},
    dag=dag)

task_4 = PythonOperator(
    task_id='sleep_for_' + 4,
    python_callable=my_sleeping_function,
    op_kwargs={'random_base': float(4) / 10},
    dag=dag)


task_0.set_upstream(run_this)
task_1.set_upstream(run_this)
task_2.set_upstream(run_this)
task_3.set_upstream(run_this)
task_4.set_upstream(run_this)

答案 2 :(得分:0)

@cwurtz是对的!

要设置任务的顺序,您可以使用priority_weight任务的参数

  

pool参数可以与priority_weight结合使用以定义队列中的优先级,并且在池中打开插槽时首先执行哪些任务。 (Read more

相关问题