django cronjob

Setup Cron Job Scheduling in Django

You know, job scheduling is crucial in all applications and there is various way of managing the jobs. In this tutorial, we will be making a Django application to demonstrate job queues. Before moving to the section just take a look into the overview of job scheduling.

What is Cron and Why?

Cron is a program, script, or command that performs regularly scheduled tasks such as report generation, backup, and so on. The tasks scheduled in cron are called cron jobs. In software development, every repeated task carried out in the background is referred to as a job. It helps you schedule and run certain tasks on your server easily. Now we can move into the setup part of a job sending email to a user in a specific interval.

Libraries like django_cron, django-crontab, etc are used to create jobs. Here we use the django-crontab package.

Step 1: Install the module using pip

pip install django-crontab

Step 2: Add django-crontab to the INSTALLED_APP in your settings.py file.

INSTALLED_APPS = [
    ...
   'django_crontab’,
]

Step 3: Now create a file named cron.py in your app directory and paste the following code.

from django.conf import settings
from django.core.mail import send_mail

def my_cron_job():
    # your functionality goes here
    subject = 'Welcome to ProgramSpeaker'
    message = f'Django cron job example'
    email_from = settings.EMAIL_HOST_USER
    recipient_list = ['recipient_email_id', ]
    send_mail( subject, message, email_from, recipient_list )

Step 4: Get back to the settings.py file and add the following code

# Cron job configuration
CRONJOBS = [("*/2 * * * *", "MyApp.cron.my_cron_job")]

# Email configuration 
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = "sender_email_address"
EMAIL_HOST_PASSWORD = "app_password"

The above cron job is scheduled to be run every 2 minutes of each hour. To know how to create an app password click here.

Step 5: Next you want to run the below command to add all the defined cron jobs to crontab. Also, make sure to run this command every time cronjobs is changed in any way.

python manage.py crontab add

If you want to list all the active cronjobs, run the following command

  python mange.py crontab show  . 

To remove all the defined cronjobs, run

 python mange.py crontab remove 

Step 6: Now the time to test out… Just run the following command and check your mail every two minutes.

python mange.py runserver  
Share this:

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top