如何手动将Celery任务标记为已完成并设置其结果

如何手动将Celery任务标记为已完成并设置其结果

本文介绍了如何手动将Celery任务标记为已完成并设置其结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个芹菜任务:

@app.task
def do_something(with_this):

    # instantiate a class from a third party library
    instance = SomeClass()

    # this class uses callbacks to send progress info about
    # the status and progress of what we're doing
    def progress_callback(data):
        # this status will change to 'finished' later
        # but the return value that I want as the task result won't be returned
        # so this is where I should mark the task as done manually
        if data['status'] == 'working':
            # I create a custom state for this task
            do_something.update_state(
                state = 'PROGRESS',
                meta = data['progress']
            )

    # adding the callback to the instance
    instance.add_callback(progress_callback)

    # use the instance to do what I want
    # this functions returns a value that I don't want as the task result
    # so leaving this function without a return statement will make it None
    instance.do_job(with_this)

如何将任务标记为手动完成?

How can I mark a task as done manually ?

在这种情况下,该函数到达末尾而没有任何 return 语句,因此我得到的 task.result None ,我要设置作为结果传递给回调函数的数据,并将任务标记为完成.

In this case the function reaches the end without any return statement so the task.result I get is None, I want to set the data passed to the callback function as the result and mark the task as done.

我尝试使用:

app.backend.mark_as_done(do_something.request.id, data)

它已成功设置了任务的状态和结果,但随后将结果设置为函数的返回值,此处为 None .

It's successfully setting the state and the result of the task but later the result is set to the return value of the function which is here None.

推荐答案

我终于找到了解决方案,该方案存储任务状态和结果,然后通过引发 Ignore 异常来忽略任务,例如:

I finally found the solution which is storing the task state and result then ignoring the task by raising an Ignore exception, for example:

from celery.exceptions import Ignore

@app.task
def do_something(with_this):

    # store the state and result manually
    # the SUCCESS state is set by this method
    app.backend.mark_as_done(
        do_something.request.id,
        the_data_to_store
    )

    # we can also use update_state which calls
    # backend.store_result just like mark_as_done
    # but we have to set the state in this case
    do_something.update_state(
        state = celery.states.SUCCESS,
        meta = the_data_to_store
    )

    # ignore the task so no other state is recorded
    # like what was happening with my function in the question
    # the task will still be acknowledged
    raise Ignore()

当您无法返回要存储的数据作为结果时,这很有用.

This is helpful when you cannot return the data that you want to store as the result.

这篇关于如何手动将Celery任务标记为已完成并设置其结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 03:33