Celery background and scheduled task processing is available for Pro tier Django projects.
Celery and Redis will already be installed in Pro project environments.
To set up Celery, first modify your settings.py
to include the following:
CELERY_BROKER_URL = "redis://localhost:6379/0"
CELERY_RESULT_BACKEND = "redis://localhost:6379/0"
CELERY_ACCEPT_CONTENT = ["json"]
CELERY_TASK_SERIALIZER = "json"
CELERY_RESULT_SERIALIZER = "json"
Now create a file named celery.py
within your app folder.
import os
from celery import Celery
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_project.settings")
app = Celery("core")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()
You may need to modify this slightly to use your own project folder name instead of the default django_project
name.
Once celery.py
has been created, visit the Settings tab and update the Celery App Path value.
Change the core
part of the value to match your project app module name.
Finally, update the __init__.py
file within your app folder.
from .celery import app as celery_app
__all__ = ('celery_app',)
You should now be able to set up Celery tasks, like in the following example.
import logging
from celery import shared_task
from datetime import datetime
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
@shared_task
def print_time():
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
logger.info(f"Current time: {current_time}")
If you want to include scheduled tasks, also add the following:
CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler"
The django_celery_beat
package should also be installed. Add the following to the project requirements.txt
file:
django-celery-beat
Update your settings.py
file to include django_celery_beat
as an app.
INSTALLED_APPS = [
...,
'django_celery_beat',
]
Once your project is re-deployed, be sure to run migrations for django-celery-beat
to work properly.
python manage.py migrate django_celery_beat
Note that using django_celery_beat
is the recommended way to support scheduled tasks on Circumeo. The default celerybeat-schedule
file-based method is not recommended, as the file can become corrupted when your instance is shut down during the deployment process.
The Celery project maintains a helpful setup guide dedicated to Django.
https://docs.celeryq.dev/en/latest/django/first-steps-with-django.html