Celery - Get task id for current task

匿名 (未验证) 提交于 2019-12-03 02:05:01

问题:

How can I get the task_id value for a task from within the task? Here's my code:

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) 

The idea is that when I create a new instance of the task, I retrieve the task_id from the task object. I then use the task id to determine whether the task has completed. I don't want to keep track of the task by the path value because the file is "cleaned up" after the task completes, and may or may not exist.

In the above example, how would I get the value of current_task_id?

回答1:

Celery does set some default keyword arguments if the task accepts them. (you can accept them by either using **kwargs, or list them specifically)

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

The list of default keyword arguments is documented here: http://ask.github.com/celery/userguide/tasks.html#default-keyword-arguments



回答2:

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

The list of all available fields is documented here: http://celery.readthedocs.org/en/latest/userguide/tasks.html?highlight=requestcontext#context



回答3:

As of celery 3.1, you can use the bind decorator argument, and have access to the current request:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!