Running Django Management Commands Periodically by Using CRONTAB Linux Command

Crontab_Django

Running Django Management Commands Periodically by Using CRONTAB Linux Command

  • I will not explain what the crontab is in this article. In a nutshell it is a tool that helps us to create periodic tasks on linux.

  • If you run crontab --help it prints out the parameters we can use

  • The following command will open nano editor and inside of it you will see some comments for guidence.

  • The nano crontab comments and description

  • Let's edit for prettier comment

  • To see the logs of CRON open a new terminal and run $ tail -f /var/log/syslog | grep CRON

  • Output

 

Django Part

  • I do have a command which named as fetch_data . As you guessed it fetches data from external api and stores into database.

  • The command file structure like this

  • virtualenv -p python3 venv created a new virtualenv instance

  • python manage.py makemigrations && python manage.py migrate

 

Crate New Crontab

  • Specify the period. I used cd command because I needed to read a json file. Use full path of your python inside virtualenv and use your manage.py full path. Here is my crontab:

  • To see cronlog.txt

  • That's it! Our crontab is running on the background and fetches data every 30 minutes.

Use Cases

  • You can fetch some data from external api.
  • You can index elasticsearch clusters
  • You can backup your database
  • and so on..
Resources

Yorumlar