Search code examples
djangodjango-celerycelerybeat

Periodic task schedules set through view functions (Django app)


I schedule repeat tasks for my Django app via including them in the CELERYBEAT_SCHEDULE dictionary in my settings.py. For instance:

CELERYBEAT_SCHEDULE = {
    'tasks.rank_photos': {
        'task': 'tasks.rank_photos',
        'schedule': timedelta(seconds=5*60),
    },
    'tasks.trim_whose_online': {
        'task': 'tasks.trim_whose_online',
        'schedule': timedelta(seconds=10*60),
    },
}

These tasks periodically run (for the life of the app).

I was wondering whether there's a way for a regular user of my app to kick off a periodic task? I.e. is there a way to control this kind of scheduling from views.py? If not, why not? And if yes, an illustrative example would be great. Thanks in advance.


Solution

  • You could use django-celery-beat package. It defines several models (e.g. PeriodicTask) and it will allow you to schedule tasks in your views by simply using those models to create or edit periodic tasks. It is mentioned in the official docs.

    There’s also the django-celery-beat extension that stores the schedule in the Django database, and presents a convenient admin interface to manage periodic tasks at runtime.