Background Tasks
BOB employs two types of tasks:
- Dynamic Tasks: Triggered during program execution, such as sending an email upon user registration.
- Periodic Tasks: Scheduled to run at regular intervals, like a cron job (e.g., every Monday at 10:00 AM).
Dynamic Tasks
Dynamic tasks can be invoked from anywhere in the code. These tasks are decorated with @shared_task
. Due to limitations in Celery (as of this documentation's writing), asynchronous methods cannot be directly decorated.
Example:
To maintain organization, dynamic tasks should be stored in files located at / <app_name> /tasks/<task_name>
.
Running Dynamic Tasks
Dynamic tasks only require the Celery worker process:
Periodic Tasks
Periodic tasks are scheduled based on a predefined timetable registered in the Celery configuration file (core/celery.py
). You must also include the paths to all files containing periodic tasks.
Example Configuration
The schedule uses cron syntax. For assistance in writing cron expressions, refer to Crontab Guru.
Defining a Periodic Task
Periodic tasks must also be defined as synchronous methods, using asyncio
internally.
Running Periodic Tasks
To execute periodic tasks, start the Celery Beat process alongside the worker:
Celery Beat monitors all registered schedules and dispatches tasks to the Celery worker at the appropriate time.
Key Notes
- Use
async_to_sync
for asynchronous methods in dynamic tasks. - Periodic tasks require both Celery Beat and the Celery worker to be running.
- Tasks should be well-organized in app-specific directories for better maintainability.
This setup ensures efficient handling of time-consuming operations and periodic processes, improving overall application performance and reliability.