Setting up or scheduling a task or cron job in Django

 

Hey folks! I’ve got something interested to share which I recently learned. You already know it, don’t you? Yes, from the title. Well then, let’s get start with it.

When working on a project, you might require to setup a cron job. Those who don’t know what a cron job is, “cron” is a utility that schedule scripts or commands to be run automatically at specified time and date or intervals and these tasks or jobs are what we call as “cron job”.
Every *nix system has a default cron utility. Crons are identified by crontab(cron-tab file), a configuration file that specifies the commands to be run periodically.

However, to set up a cron job in Django, we can make use of a third party module which I found really useful, django-crontab

How to write a cron job?

Before we go any further, we must understand the syntax in which a cron job is defined. Yes, a cron job has a specified format which can be understand by the cron utility. The main part of a cron is its timing syntax which defines the schedule at which the job has to be run periodically.

It consist of five parts order-wise i.e. starting from minute to defining week day.

  1. Minute (0 – 59)
  2. Hour (0 – 23)
  3. Day of the month(1 – 31)
  4. Month (1 – 12)
  5. Week day (0 – 6)

The most simplified syntax for a cron can be seen as

* * * * * [job]

For each field, we have used an asterisk(*) which implies all the possible numbers for a position. The above cron job is scheduled to run every minute. Let’s see a few more examples to understand it better

2 * * * * [job]

The above timing definition implies that the job is scheduled to be run at 2 minute of every hour ie 00:02, 01:02, 02:02, 03:02 et cetera.

10 8 * * * [job]

The above syntax corresponds to the job schedule at 8:10 of every day

*/2 * * 3 * [job]

Now, this is something different. Here we have used the “/”(division) operator. You may notice I have divided the minute value by 2 i.e. I want the cron job to run at every 2 minute but I have as well defined the value of month as 3 which implies the above job is scheduled to be run at every 2nd minute of 3rd month for all hours and for all days.

Just like “/”, some other symbols are also used to make a cron job more specific. For e.g. “,”(comma) is used to define multiple values for the same field. Let’s see an example of this also

2,4,6 * * * * [job]

The above job will run three times every hour at 2nd, 4th and 6th minute.

Similarly “-“(dash) can be used to define the range of values for a field. For e.g.

0 6-8 * * * [job]

The above job will run once every hour between 6:00 am and 8:00 am every day.

You may look for more examples of a cron job schedule definition here.

Steps to setup a cron job in Django

Now let’s get started with setting up the cron job in Django environment. We just need to follow some simple steps:-

  1. We first need to install the module using pip. I’ll suggest you to do it in a virtual environment in which all other dependencies of your project are installed.
    pip install django-crontab
  2. Add django_crontab to INSTALLED_APPS in your django project’s settings.py file
    INSTALLED_APPS = [
        'django_crontab',
        ...
    ]
  3. Create a file anywhere within your django’s project according to your module directory structure for e.g. myapp/cron.py and define the function which you want to be executed automatically via cron. This will be your cron job.
    def my_cron_job():
        # your functionality goes here
  4. Add the following line to your django project’s settings.py file
    CRONJOBS = [
        ('*/2 * * * *', 'myapp.cron.my_cron_job')
    ]

    We define a cron just as above. The above cron job is scheduled to be run at every 2nd minute of each hour.
    You can also provide positional or keyword arguments to the cron definition for the cron method as

    CRONJOBS = [
        ('0 0 1 * *', 'myapp.cron.other_cron_job', ['pos_arg1', 'pos_arg2'], {'verbose': 'key_arg'}),
    ]
  5. Run this command to add all the defined CRONJOBS to crontab(*nix cron utility). Make sure to run this command every time CRONJOBS is changed in any way.
    python manage.py crontab add
  6. To get all the active CRONJOBS, run the following command
    python manage.py crontab show
  7. To remove all the defined CRONJOBS from crontab, run the following command
    python manage.py crontab remove

That’s all! Wasn’t it easy? Few simple steps and your work is done. To see the changes, once you add the CRONJOBS to crontab, run the django server

python manage.py runserver

References

  1. https://en.wikipedia.org/wiki/Cron
  2. https://crontab.guru/

Comments

Popular posts from this blog

Documentation is Very vital before you develop any system or app

Everything you need to know when developing an on demand service app

Steps followed when creating a new software