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

96 投票
3 回答
75363 浏览
提问于 2025-04-16 01:39

我想知道怎么在任务内部获取任务的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来判断任务是否完成。我不想通过 path 值来跟踪任务,因为文件在任务完成后会被“清理”,可能会不存在。

在上面的例子中,我该怎么获取 current_task_id 的值呢?

3 个回答

93

从celery 3.1开始,你可以使用bind这个装饰器参数,这样你就能访问当前的请求信息了:

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

更新:使用Balthazar的答案适用于Celery 3.1及以上版本

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

欢迎给他的答案点赞。

旧答案:

从Celery 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

10

如果你的任务可以接受一些特定的参数,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

撰写回答