代码之家  ›  专栏  ›  技术社区  ›  mattbasta

芹菜-获取当前任务的任务id

  •  64
  • mattbasta  · 技术社区  · 14 年前

    如何从任务中获取任务的任务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 回复  |  直到 14 年前
        1
  •  8
  •   asksol    14 年前

    如果任务接受,芹菜会设置一些默认关键字参数。 (您可以通过使用**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

        2
  •  125
  •   Afshin Mehrabani Mohd Jafar    5 年前

    自Celery2.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

        3
  •  72
  •   Balthazar Rouberol Dave Kirby    9 年前

    从芹菜3.1开始,你可以使用 bind

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