How to Setup Cron Job Task Scheduling in Django?

Published On: 10/12/2022 | Category: Django


Hi Dev,

In this tute, we will discuss how to setup cron job task scheduling in django. In this article, we will implement a how to use cron job in django. step by step explain how to use django-crontab. you can understand a concept of django-crontab task scheduling example. you will do the following things for django cron tab task scheduling tutorial.

Cron is a programme that allows Unix system users to automatically execute scripts, commands, or software at a predefined date and time, or according to a predefined cycle.

For this example, we'll use django-crontab. Open a terminal in your project's root directory and type

Here i explained simply step by step example of how to setup cron job task scheduling in django.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example

Step 2: Create a App

Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python3 manage.py startapp core

Step 3: Installing the django-crontab library

In this section first of all we need to install django-crontab library through below following command:

pip install django-crontab

Step 4: Create cron.py File

Assume our file is core/cron.py for this example. In this file, we must define the function that will be executed automatically by cron.

core/cron.py
import logging
# Get an instance of a logger
logger = logging.getLogger(__name__)

def my_cron_job():
    print('Hello World')
    logging.info("It's Working!")

Step 5: Update setting.py

Then update INSTALLED_APPS within our settings.py file to notify Django about the app.

settings.py

....
INSTALLED_APPS = [
    
    'core',
    'django_crontab'
]

import logging

LOGGING = {
    'version': 1,
    # The version number of our log
    'disable_existing_loggers': False,
    'formatters': {
        'file': {
            'format': '%(asctime)s %(name)-12s %(levelname)-8s: %(message)s'
        }
    },
    # django uses some of its own loggers for internal operations. In case you want to disable them just replace the False above with true.
    # A handler for WARNING. It is basically writing the WARNING messages into a file called WARNING.log
    'handlers': {
        'file': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'filename': BASE_DIR / 'info.log',
            'formatter':'file'
        },
    },
    # A logger for WARNING which has a handler called 'file'. A logger can have multiple handler
    'loggers': {
       # notice the blank '', Usually you would put built in loggers like django or root here based on your needs
        '': {
            'handlers': ['file'], #notice how file variable is called in handler which has been defined above
            'level': 'INFO',
            'propagate': True,
        },
    },
}

CRONJOBS = [
    ('*/1 * * * *', 'core.cron.my_cron_job') #This cron run every minute
]

The above cron job is set to run every hour on the one minute.

Keyword or positional arguments are also acceptable:

CRONJOBS = [
    (‘0 0 1 * *’, core.cron.other_cron_job’, [‘pos_arg1’, ‘pos_arg2’], {‘verbose’: ‘key_arg’}),
]

You can add, show and remove this below following command:

python manage.py crontab add
python manage.py crontab show
python manage.py crontab remove

Output

So, now you can check this your info.log file and see the below output.

2022-12-10 04:31:02,599 root         INFO    : It's Working!
2022-12-10 04:32:03,151 root         INFO    : It's Working!

I hope it will help you....

Happy Coding!