[Answered ]-Django template – Create a cron job to wish an happy birthday

2πŸ‘

βœ…

A simple solution would be to create a custom management command which will send the happy birthday emails of the day and run it every day via a cronjob.

This an example custom command, yours will probably be different, depending on how you store your user data:

# app/management/commands/send_daily_birthday_greetings.py
"""
Custom management command that sends an email to all users
born on the current day and month.
"""

from django.core.management import BaseCommand
from django.core.mail import send_mail
from django.utils import timezone
from someplace import User



class Command(BaseCommand):
    def handle(self, **options):
        today = timezone.now().date()
        for user in User.objects.filter(birth_date__day=today.day, birth_date__month=today.month):
            subject = 'Happy birthday %s!' % user.first_name
            body = 'Hi %s,\n...' + user.first_name
            send_mail(subject, body, 'contact@yourdomain.com', [user.email])

Then edit your crontab configuration with crontab -e this way:

# m h  dom mon dow   command
0 10 * * * /path/to/your/python/executable/python /path/to/your/manage.py send_daily_birthday_greetings

This will send the emails at 10h00 every day, you may change the time as you wish.

πŸ‘€aumo

0πŸ‘

In building on aumo’s answer, if you’re deploying to a PaaS, like Heroku for instance, and cannot schedule cron jobs, you can use a combination of honcho and management commands to schedule your periodic tasks. Sometimes it can also be nice to keep it all a part of the application rather than having to edit other system files like cron. honcho

For example, your Procfile might look like this:

web: gunicorn config.wsgi:application
tasks: honcho -f ProcfileHoncho start

Your honcho file might look like this:

clock: python clock.py
reports: python app_name/tasks/reports.py

And your clock file calls the management commands:

import os
import subprocess
from apscheduler.schedulers.blocking import BlockingScheduler

sched = BlockingScheduler()

# Morning updates. Times in UTC time.
@sched.scheduled_job('cron', hour=11)
def birthdays():
    os.system('python manage.py send_daily_birthday_greetings')
πŸ‘€AuxProc

Leave a comment