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
?
To obtain the value of task_id you first have to create an instance of that class, afterwards accessing async_result_instance. task_id will return you the real id. In your updated code: (Code not tested since I don't have celery installed.)
The "shared_task" decorator allows creation of Celery tasks for reusable apps as it doesn't need the instance of the Celery app. It is also easier way to define a task as you don't need to import the Celery app instance.
The bind argument means that the function will be a “bound method” so that you can access attributes and methods on the task type instance.
Celery is an open source asynchronous task queue or job queue which is based on distributed message passing. While it supports scheduling, its focus is on operations in real time.
@task(bind=True) def do_job(self, path): cache.set(self.request.id, operation_results)
Feel free to upvote his answer.
Since Celery 2.2.0, information related to the currently executed task is saved to task.request
(it's called «the context»). So you should get task id from this context (not from keyword arguments, which are deprecated):
@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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With