Implementing Scheduled Tasks in Django with django‑crontab and APScheduler
This article explains how to run periodic jobs in a Django project by using the django‑crontab plugin and the APScheduler library, covering installation, configuration in settings.py, and the commands needed to add, remove, and view scheduled tasks on Linux systems.
When building a Django application, you may need to execute tasks at regular intervals; this guide surveys two common approaches.
1. django‑crontab plugin
Install the package with pip install django-crontab . Add 'django_crontab' to INSTALLED_APPS in settings.py and define the cron jobs, for example:
CRONJOBS = [
('*/1 * * * *', 'crontab_test.mycron.my_cron', '>> ' + os.path.join(BASE_DIR, 'info.log') + ' 2>&1')
]Use the management commands to control the jobs:
python manage.py crontab add – write jobs to the system crontab
python manage.py crontab remove – delete the jobs
python manage.py crontab show – list current jobs
Note: this method relies on the Linux crontab utility.
2. APScheduler
Install with pip install apscheduler and add 'django_apscheduler' to INSTALLED_APPS . After running python manage.py migrate , you can define and start schedulers in your code. A typical start command is:
sched.start()This approach works cross‑platform and does not depend on the system crontab.
360 Quality & Efficiency
360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.