Task 9
Use case
An example of a heavy task is sending emails, we want to send an artist user an email in these situations:
- When an artist creats an album, we want to send an email to their address congratulating them.
- We want to run a periodic task every 24 hours to see if any artists haven't created an album in the past 30 days, if so, we send them an email letting them know that their inactivity is causing their popularity on our platform to decrease.
Task
- Install
redis-server
on your machine - Install
celery
as a project dependency - Install
redis
as a project dependency - Integrate celery with the project
- Allow for defining celery config options in
settings.py
module - Celery config options should have the prefix
CELERY_CONF
- for example:
CELERY_CONF_TIMEZONE
,CELERY_CONF_RESULT_BACKEND
- for example:
- Allow for defining celery config options in
- Setup a gmail email to use for this project to send emails from
- Use
django-environ
to import your secure environment variables like the redis server address or email credentials - Define a task in
albums/tasks.py
or whateverrelated_name
you provided for celery'sautodiscover_tasks()
method - Define a task that receives the artist and album data you need as arguments and send the artist a congratulation email.
- remember: the data the task receives must be serializable
- Use a post-save signal or override
Album.save()
and each time an album is created asynchronously call the task that you defined in the previous step - Define another task that achieves
Use case 2.
and use celery's default beat schedulerPersistentScheduler
to run the task every 24 hours- Define the
beat_schedule
insettings.py
like so:
CELERY_CONF_BEAT_SCHEDULE = { 'add-every-30-seconds': { 'task': 'tasks.add', 'schedule': 30.0, 'args': (16, 16) }, }
- Read: There is another way to define periodic tasks during runtime by storing the beat schedule in django's database and using django admin to define each task's schedule. See
django-celery-beat
- Define the