没有结果的 Celery 任务写入结果后端

问题描述 投票:0回答:3

我有一些任务应该返回结果,而有些任务则不会。 我想强制不应该返回结果的任务不在结果后端写入任何内容(例如无)。我怎样才能在 Celery 中实现这一点?

例如,这是我的任务:

@app.task
def taskWithResult():
    # ...code...
    return res

@app.task
def taskWithNoResult():
    # ...code without return...

而且我还有一些其他任务的特殊队列,这些任务也不会返回任何结果,我可以将该队列标记为不得写入结果后端的任务吗?

celery django-celery
3个回答
20
投票

从 celery 文档中,您可以将忽略结果标志设置为 True。 http://docs.celeryproject.org/en/latest/reference/celery.app.task.html?highlight=default_retry_delay#celery.app.task.Task.ignore_result

例如:

@app.task(ignore_result=True)
def taskWithNoResult():
    # ...code without return..

6
投票

全局配置

app.conf.task_ignore_result = True

本地关闭返回任务结果:

@app.task(ignore_result=True)
def add(...):

如果您只想将任务执行失败的异常结果返回并持久化以供后续排查分析,那么可以在使用数据库作为结果后端时应用以下配置:

仅在结果后端存储任务错误。

app.conf.task_ignore_result = True
app.conf.task_store_errors_even_if_ignored = True

0
投票

如果您想有条件地执行此操作,您可以使用

setattr(self.request, "ignore_result", True)

@shared_task(bind=True)
def run_process(self):
try:
    processor = Processor(strategy_token)
    completed = execute_strategy()
    if not completed:
        setattr(self.request, "ignore_result", True)
except Exception as error:
    logger.exception(error)
© www.soinside.com 2019 - 2024. All rights reserved.