2010-07-21 67 views
55

如何從任務中獲取任務的task_id值?這裏是我的代碼:芹菜 - 獲取當前任務的任務ID

from celery.decorators import task 
from django.core.cache import cache 

@task 
def do_job(path): 
    "Performs an operation on a file" 

    # ... Code to perform the operation ... 

    cache.set(current_task_id, operation_results) 

的想法是,當我創建任務的新實例,我檢索任務對象的task_id。然後我使用任務ID來確定任務是否完成。 I 不要想要跟蹤path值的任務,因爲文件在任務完成後「清理乾淨」,並且可能存在也可能不存在。

在上面的例子中,我將如何得到current_task_id的值?

回答

7

如果任務接受它,Celery會設置一些默認關鍵字參數。 (您可以通過使用** kwargs要麼接受他們,或者列出他們專門)

@task 
def do_job(path, task_id=None): 
    cache.set(task_id, operation_results) 

的默認關鍵字參數列表記錄在這裏: http://ask.github.com/celery/userguide/tasks.html#default-keyword-arguments

+28

這是從Celery 2.2.0(請參閱下面的答案)已棄用。 – Simon 2011-11-16 06:47:33

96

由於芹菜2.2.0,相關信息當前執行的任務被保存到task.request(它被稱爲「上下文」)。所以,你應該從這個方面獲得任務ID(不是從關鍵字參數,這是不建議使用):

@task 
def do_job(path): 
    cache.set(do_job.request.id, operation_results) 

所有可用字段列表記錄在這裏: http://celery.readthedocs.org/en/latest/userguide/tasks.html?highlight=requestcontext#context

+0

你可以在任務之外得到這個ID嗎?例如運行任務,獲取id並在任務完成時檢查此id。 – DominiCane 2013-06-18 16:58:41

+0

是的,你可以從AsyncResult獲得id,然後通過id重新創建AsyncResult,檢查文檔http://docs.celeryproject.org/en/latest/reference/celery.result.html – HighCat 2013-06-20 21:30:23

34

如芹菜3.1,你可以使用裝飾器參數bind,並有權訪問當前請求:

@task(bind=True) 
def do_job(self, path): 
    cache.set(self.request.id, operation_results) 
+0

謝謝你的新回覆。奇蹟般有效 – 2017-01-21 21:11:01