Is there a way to determine, programatically, that the current module being imported/run is done so in the context of a celery worker?
We've settled on setting an environment variable before running the Celery worker, and checking this environment variable in the code, but I wonder if there's a better way?
Adding a environment variable is a good way to check if the module is being run by celery worker. In the task submitter process we may set the environment variable, to mark that it is not running in the context of a celery worker.
But the better way may be to use some celery signals which may help to know if the module is running in worker or task submitter. For example, worker-process-init signal is sent to each child task executor process (in preforked mode) and the handler can be used to set some global variable indicating it is a worker process.
As of celery 4.2 you can also do this by setting a flag on the
worker_ready
signalin
celery.py
:Now you can check within your task by using the global app instance to see whether or not you are running. This can be very useful to determine which logger to use.
Depending on what your use-case scenario is exactly, you may be able to detect it by checking whether the request id is set:
If you invoke the above as
foo.delay()
then the task will be sent to a worker andself.request.id
will be set to a unique number. If you invoke it asfoo()
, then it will be executed in your current process andself.request.id
will beNone
.You can use the
current_worker_task
property from theCelery
application instance class. Docs here.With the following task defined:
You can run the following on a python shell:
Note: Obviously for
test_task.delay()
to succeed, you need to have at least one celery worker running and configured to load tasks fromwhatever_app.tasks
.It is a good practice to start workers with names, so that it becomes easier to manage(stop/kill/restart) them. You can use
-n
to name a worker.Now, in your script you can use
app.control.inspect
to see if that worker is running.You can read more about this in celery worker docs
Simple,
http://percentl.com/blog/django-how-can-i-detect-whether-im-running-celery-worker/