[Solved]-How do I run periodic tasks with celery beat?

10πŸ‘


Celery beat command

celery -A proj worker -l info -B --scheduler django_celery_beat.schedulers:DatabaseScheduler

This command has used for start the celery beat.

Firstly add the django_celery_beat module in installed apps in settings file.

And then apply the django migrate command, this will create the tables in admin pannel.

After completing all the process like in celery file and create task in tasks.py.

you will apply the beat command as mentions in above.


proj/settings.py

INSTALLED_APPS = [

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'django_celery_beat',
]

REDIS_URL = "redis://localhost:6379/1"

CELERY_BROKER_URL=REDIS_URL

CELERY_RESULT_BACKEND=REDIS_URL

CELERY_ACCEPT_CONTENT = ['application/json']

CELERY_RESULT_SERIALIZER = 'json'

CELERY_TASK_SERIALIZER = 'json'

CELERY_BEAT_SCHEDULE = {

        'task-first': {
        'task': 'app.tasks.one',
        'schedule': timedelta(seconds=1)
       },
      'task-second': {
        'task': 'app.tasks.two',
        'schedule': crontab(minute=0, hour='*/3,10-19')
      }
}

proj/celery.py

from celery import Celery

from django.conf import settings

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

app = Celery('proj')

app.config_from_object('django.conf:settings')

app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

proj/__init.py__

from .celery import app as celery_app

**__all__** = ['celery_app']
πŸ‘€Manish Kumar

2πŸ‘

When you ran your worker, did it say that app.tasks.one and app.tasks.two are registered tasks? If they do not appear there as registered tasks then your beat is scheduling tasks that can’t be executed. – They will just wait in the queue, and eventually expire. Another way to check whether you have them registered is via celery -A proj.celeryapp inspect registered (change proj.celeryapp to whatever is the location of your Celery application).

πŸ‘€DejanLekic

Leave a comment