I'd like a celery task to be able to get the name of the worker executing it, for logging purposes. I need to handle this from within the task, rather than querying the broker directly. Is there a way to do this? I'm using celery with RabbitMQ, if that matters.
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: @celery.
celery -A yourproject. app inspect status will give the status of your workers. celery -A yourproject. app inspect active will give you list of tasks currently running, etc.
When you run a celery worker, it creates one parent process to manage the running tasks. This process handles the book keeping features like sending/receiving queue messages, registering tasks, killing hung tasks, tracking status, etc.
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.
I also needed the worker name for reporting purposes so I tried @cacois solution but it doesn't seem to work with eventlet (current_process() doesn't have an initargs attribute). So I'll leave my solution here for future references:
from celery import task
@task(bind=True)
def getName(self):
return self.request.hostname
The name of the attribute sounds weird to me, but that contains the name specified with the "-n" option when launching the worker. self works like you would expect from a class method, you don't need to specify it when calling the function (eg: getName.delay()).
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