如何使芹菜任务从任务内部失败? [英] How to make a celery task fail from within the task?

查看:60
本文介绍了如何使芹菜任务从任务内部失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,我想使芹菜任务从该任务中失败.我尝试了以下方法:

Under some conditions, I want to make a celery task fail from within that task. I tried the following:

from celery.task import task
from celery import states

@task()
def run_simulation():
    if some_condition:
        run_simulation.update_state(state=states.FAILURE)
        return False

但是,任务仍然报告成功:

However, the task still reports to have succeeded:

任务sim.tasks.run_simulation [9235e3a7-c6d2-4219-bbc7-acf65c816e65]在1.17847704887s成功:False

Task sim.tasks.run_simulation[9235e3a7-c6d2-4219-bbc7-acf65c816e65] succeeded in 1.17847704887s: False

似乎只能在任务运行时以及完成后才能修改状态-芹菜将状态更改为它认为是结果的状态(请参阅

It seems that the state can only be modified while the task is running and once it is completed - celery changes the state to whatever it deems is the outcome (refer to this question). Is there any way, without failing the task by raising an exception, to make celery return that the task has failed?

推荐答案

我得到了

I got an interesting reply on this question from Ask Solem, where he proposes an 'after_return' handler to solve the issue. This might be an interesting option for the future.

与此同时,我通过在要使其失败的任务中简单地从任务中返回字符串'FAILURE'来解决此问题,然后按如下所示进行检查:

In the meantime I solved the issue by simply returning a string 'FAILURE' from the task when I want to make it fail and then checking for that as follows:

result = AsyncResult(task_id)
if result.state == 'FAILURE' or (result.state == 'SUCCESS' and result.get() == 'FAILURE'):
    # Failure processing task 

这篇关于如何使芹菜任务从任务内部失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆