2014-09-13 20 views
5

我有這樣的任務芹菜:如何手動將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) 

我怎麼能任務標記爲手動完成?

在這種情況下,函數到達最後而沒有任何return語句,因此我得到的task.resultNone,我想設置傳遞給回調函數的數據作爲結果並將任務標記爲完成。

我試着使用:

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

它成功設置狀態和任務的結果,但後來的結果被設定爲是這裏None函數的返回值。

回答

5

我終於發現這是存儲任務狀態和結果,然後通過引發Ignore例外忽略任務的解決方案,例如:

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() 

這是有用的,當你不能回到你想要的數據,作爲結果存儲。

相關問題