SoFunction
Updated on 2024-11-13

Example of using django-crontab to implement a timed task

Today, I intend to add a timed task to my Django application to regularly perform some periodic checks, so I thought of using the django-crontab plugin to meet my needs, here is how to use this plugin.

First install the django-crontab plugin using pip

pip install django-crontab

Create the script and method to be executed periodically, here assume the script name is called and the content is as follows:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

def check():
  print "hello django-crontab"

Then add the app to your application's files.

INSTALLED_APPS = (
  ...
  'django_crontab',
)

Also add the CRONJOBS configuration to the file as follows:

CRONJOBS = [
  ('*/1 * * * *', '','>>/tmp/')
]

Among them:
- The first argument is a cron expression that defines the execution time of the timed task.
- The second argument is the module and function to be executed.
- The third parameter is the path to the log file when the timing script is executed.

Having defined the timed tasks and scripts, here's how to make them work.

First, look at the existing cron jobs on the system

python  crontab show 

Adding and modifying cron jobs

python  crontab add 

Delete cron job

python  crontab remove

This is the whole content of this article.