Celery - Get task ID for current task

How can I get the task_id value for a task from a task? Here is 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. Then I use the task ID to determine if the task has completed. I do not want to track the task with the path value, because the file is "cleaned up" after the task is completed and may or may not exist.

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

+69
python django celery
Jul 21 '10 at 18:02
source share
3 answers

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

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

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

+9
Jul 21 '10 at 20:17
source share
— -

Starting with version of task.request 2.2.0, information related to the task currently being performed is stored in task.request (it is called the "context"). Thus, you should get the task identifier from this context (and not from keyword arguments that are out of date):

 @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

+112
Nov 11 2018-11-11T00:
source share

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

 @task(bind=True) def do_job(self, path): cache.set(self.request.id, operation_results) 
+49
Dec 14 '15 at 10:27
source share



All Articles