Celery 4 not auto-discovering tasks

大憨熊 提交于 2019-12-06 05:04:01

I had a similar issue, and the solution was to add the include kwarg to your celery call.

The include argument is a list of modules to import when the worker starts. You need to add our tasks module here so that the worker is able to find our tasks.

app = Celery('myproject', 
             backend = settings.CELERY.get('backend'),
             broker = settings.CELERY.get('broker'),
             include = ['ingest.tasks.web', ... ])

Check out http://docs.celeryproject.org/en/latest/getting-started/next-steps.html#proj-celery-py for more information

Just posting this here (I don't know why it works)

from django.conf import settings

app.config_from_object(settings, namespace='CELERY')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True)

force=True seems to be the solution

Another thing that works is calling django.setup() before instantiating celery.

from __future__ import absolute_import, unicode_literals
import os

import django

from celery import Celery


django.setup()  # This is key


# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')

app = Celery('notifs')
app.config_from_object('django.conf:settings', namespace='CELERY')

app.autodiscover_tasks()

This method avoids force=True, import django.conf.settings and seems cleaner to me. Though i still have no idea why you need to call django.setup because It isn't stated in the docs.

The accepted answer doesn't work for me. I am using celery 4.1.0 and django 2.0.2 and this same thing happens to me...it shows no tasks being found except for the sample "debug_task", even though I have several installed apps with Celery tasks, with should have been found via the call to app.autodiscover_task().

I have tried manually adding them to CELERY_IMPORTS as well as tried the suggestions mentioned above. Same outcome. Been blowing through hours upon hours with no luck.

from django.conf import settings    
celery_app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

You can add the above line to make celery to autodiscover all tasks written in the whole project. This is working for me.

I found the bigger problem was that Celery wasn't setting my custom Celery() instance as the current app. To fix it, I had to modify my celery_init.py to include:

from celery._state import _set_current_app

# setup my app = Celery(...)

_set_current_app(app)

Even i am not sure, if this will work. But i guess it worked for me:

There is a section in the same documentation you mentioned:

enter image description here

After this i removed CELERY_IMPORTS and it could register the tasks from all apps inside my project

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