【问题标题】:Celery - Get task id for current taskCelery - 获取当前任务的任务 ID
【发布时间】:2011-03-19 03:44:00
【问题描述】:

如何从任务中获取任务的 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)

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

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

【问题讨论】:

    标签: python django celery


    【解决方案1】:

    更新:使用 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

    【讨论】:

    • 你能在任务之外得到这个ID吗?例如运行任务,获取 id 并检查任务是否完成。
    • 是的,你可以从 AsyncResult 中获取 id,然后通过 id 重新创建 AsyncResult,查看文档docs.celeryproject.org/en/latest/reference/celery.result.html
    • 如果您有 Celery 3+,请使用 Balthazar 的答案。它更加清晰和直接。
    【解决方案2】:

    从 celery 3.1 开始,您可以使用 bind 装饰器参数,并可以访问当前请求:

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

    【讨论】:

    • 感谢您的新回复。像魅力一样工作
    • 是否也可以知道它是否是周期性任务?
    【解决方案3】:

    如果任务接受,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

    【讨论】:

    • 自 Celery 2.2.0 起已弃用(请参阅下面的答案)。
    猜你喜欢
    • 2013-12-09
    • 2018-11-27
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 2023-02-23
    • 2017-06-27
    相关资源
    最近更新 更多