Celery - 获取当前任务的任务ID

mat*_*sta 71 python django celery

如何从任务中获取任务的task_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)
Run Code Online (Sandbox Code Playgroud)

我的想法是,当我创建任务的新实例时,我task_id从任务对象中检索它.然后我使用任务ID来确定任务是否已完成.我不想通过path值跟踪任务,因为文件在任务完成后被"清理",并且可能存在也可能不存在.

在上面的例子中,我将如何获得值current_task_id

Ale*_*okk 113

从Celery 2.2.0开始,与当前执行的任务相关的信息被保存到task.request(它被称为"上下文").所以你应该从这个上下文中获取任务id(而不是来自不推荐使用的关键字参数):

@task
def do_job(path):
    cache.set(do_job.request.id, operation_results)
Run Code Online (Sandbox Code Playgroud)

此处记录了所有可用字段的列表:http: //celery.readthedocs.org/en/latest/userguide/tasks.html?highlight = requestcontext #context

  • 你能在任务之外得到这个id吗?例如运行任务,获取 id 并检查此 id 任务是否完成。 (2认同)

Bal*_*rol 51

从芹菜3.1开始,您可以使用binddecorator参数,并可以访问当前请求:

@task(bind=True)
def do_job(self, path):
    cache.set(self.request.id, operation_results)
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的新回复.奇迹般有效 (2认同)

ask*_*sol 9

如果任务接受它们,Celery会设置一些默认关键字参数.(您可以使用**kwargs接受它们,或者专门列出它们)

@task
def do_job(path, task_id=None):
    cache.set(task_id, operation_results)
Run Code Online (Sandbox Code Playgroud)

此处记录了默认关键字参数列表:http: //ask.github.com/celery/userguide/tasks.html#default-keyword-arguments

  • 从Celery 2.2.0开始,这已被弃用(参见下面的答案). (31认同)