简体   繁体   中英

How can I make a Celery Task run only after the previous task is successful

I have two celery tasks, I want the second task to run only if the first is successful, something like this

@celery.task()
def add_together(a, b):
    return a + b

@celery.task()
def subtract(a, b):
    return a - b

First call

add_together.delay(2,2)

Second call

subtract.delay(4,2)

I want the second to run only if the first is successful

You can do this by chaining your tasks

@celery.task()
def add_together(a, b):
    return a + b

@celery.task()
def subtract(a, b):
    return a - b

celery_chain = add_together.s(2,2) | subtract.s(2)
celery_chain()

The returned result from add_together will be passed to the first argument of subtract in the example above. Hence, why I omitted the '4' in subtract.delay(4,2)

Instead of executing tasks in chain as proposed by @pAulseperformance because the second task will be executed though the first failed. You can use callbacks to execute a task only if the previous one succeed.

add_together.apply_async((2, 2), link=subtract.si(4,2))

For more about callbacks checkout this or this for task signature

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM