Home    /    Blogs    /    Django
How to use cronjobs in Django project with django-crontab

Dear Learner,
We are assuming that you know the concept of cronjobs. if not then take a look at the below๐Ÿ‘‡ lines. You will get a basic understanding of it.

"A cronjob is a scheduled task [report creation, database cleaning, and sending emails] that runs automatically without any manual intervention at specific time intervals. Cronjobs are managed by corn daemon which is a background service that handles scheduling and execution of these tasks."

Cronjobs have a specific syntax. The basic structure looks like this ๐Ÿ‘‡

* * * * * command_to_be_executed

Here 5 stars is nothing but a cron expression that tells how and when to repeat this cronjob. And at the place of command_to_be_executed is going to be your tasks path.

To use cronjobs in Django projects there is a package called django-crontab which is a very powerful tool that allows us to do all these things effortlessly. We will walk you through the steps.

Prerequisites

Before jumping directly into working with cronjobs these are the things we required:

1. Installation of Python & Django on your local machine or server.

2. You should have a Django project. If not click here

Install django-crontab package

Now install a package with pip

pip install django-crontab

After installation is done we have to follow some steps given below

Add django_crontab into your INSTALLED_APPS inside settings.py

# settings.py

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

Configuration of cronjobs

Before configuration, you have to create a script that is going to work as a cronjob. Inside your APP create a script APP/cronscript.py then write your logic.

# Cronjob

Def myCron():
    # Write your logic here

Now you have to add your cronjobs to your settings.py as given below

# settings.py

CRONJOBS = [
    ('*/5 * * * *', 'your_app.cronscript.myCron'),
    # Add more cron jobs as needed here in this list
]

Install cronjobs to crontab

By installing your cronjobs to crontab they will be executed at their scheduled time and intervals. To do this follow the below command

python manage.py crontab add

This will install your cronjobs mentioned in the settings.py file.

And it will give you IDs for all of your cronjobs. Please take a look selected values.

With these IDs you can manage your crons like show your cron, remove your cron, run your cron all these things can be done.

Managing cron Jobs

Run

With this command, you can run a particular cronjob.

python manage.py crontab run fbefaf90a92771be066062500ec446b6

Show

With this command, You can see all cronjobs in this project.

python manage.py crontab show

Remove

With this command, You can remove all cronjobs in this project.

python manage.py crontab remove

For more information please follow this link

Recommended for you
mongodb with pymongo
Updated On  
Views

652