Django celery beat not able to locate app to schedule task

I’m trying to schedule a task in celery.

celery.py inside the main project directory

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from celery.schedules import crontab

os.environ.setdefault('DJANGO_SETTINGS_MODULE','example_api.settings')

app = Celery('example_api')

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

app.conf.beat_schedule = {
    'add_trades_to_database_periodically': {
        'task': 'transactions.tasks.add_trades_to_database',
        'schedule': crontab(minute='*/1'),
        # 'args': (16,16),
    },
}

app.autodiscover_tasks()

The project has a single app called transactions.

function inside transactions/tasks.py

@task(name="add_trades_to_database")
def add_trades_to_database():
    start_date = '20000101' #YYYYDDMM
    end_date = '20150101'
    url = f'https://api.example.com/trade-retriever-api/v1/fx/trades?fromDate={start_date}&toDate={end_date}'
    content = get_json(url)
    print(content)
    save_data_to_model(content,BulkTrade)

settings.py

"""
Django settings for nordea_api project.

Generated by 'django-admin startproject' using Django 3.2.7.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

from pathlib import Path
import os
import environ

env = environ.Env()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
env.read_env(env.str('BASE_DIR', '.env'))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'example'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',

    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',
    'rest_auth.registration',

    'allauth',
    'allauth.account',
    'allauth.socialaccount',

    'corsheaders',

    'transactions.apps.TransactionsConfig',

    'django_celery_beat',
]

# REST_FRAMEWORK = {
#     'DEFAULT_PERMISSION_CLASSES':[
#         'rest_framework.permissions.IsAuthenticated',
#     ]
# }

CELERY_TIMEZONE = "UTC"
# CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'

DEFAULT_AUTHENTICATION_CLASSES = [
    'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.TokenAuthentication',
]

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = os.environ.get('EMAIL')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD')
DEFAULT_FROM_EMAIL = os.environ.get('EMAIL')

SITE_ID = 1

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'example_api.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'example_api.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'example_transaction',
        'USER': 'myUser',
        'PASSWORD': os.environ.get('DATABASE_PASSWORD'),
        'HOST':'localhost',
        'PORT':'',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


I’m using rabbitmq-server for taskqueues.

  • My rabbitmq-server is active all the time.
  • Other celery task work absolutely fine.(I’ve tried implementing an email function which works well using celery).

I start celery worker and beat using

celery -A project worker -l info
celery -A project beat -l info

Following error appears in the worker terminal

The full contents of the message body was:
'[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b)
Traceback (most recent call last):
  File "/home/......./env/lib/python3.8/site-packages/celery/worker/consumer/consumer.py", line 581, in on_task_received
    strategy = strategies[type_]
KeyError: 'transactions.tasks.add_trades_to_database'

I’m using ubuntu.

Answer

You have explicitly named the task "add_trades_to_database"

@task(name="add_trades_to_database")
def add_trades_to_database():
    ...

Yet, you are scheduling the task under the name "transactions.tasks.add_trades_to_database"

app.conf.beat_schedule = {
    'add_trades_to_database_periodically': {
        'task': 'transactions.tasks.add_trades_to_database',
        'schedule': crontab(minute='*/1'),
    },
}

Solutions you can choose from:

  1. Don’t explicitly set a name for the task. Celery would set a default name for it based on the module names and the function name as documented. The beat schedule remains the same (assuming add_trades_to_database is located in my_proj/transactions/tasks.py::add_trades_to_database)
    @task
    def add_trades_to_database():
        ...
    
  2. Or you can just change the beat schedule to refer to the explicitly set name.
    app.conf.beat_schedule = {
        'add_trades_to_database_periodically': {
            'task': 'add_trades_to_database',
            'schedule': crontab(minute='*/1'),
        },
    }
    

To emphasize, choose only one out of these 2 solutions, because doing both would obviously still fail for the same reason.

Also, note that when using Django, the convention is to use the decorator @shared_task so you might want to change your tasks to:

from celery import shared_task


@shared_task
def add_trades_to_database():
   ...