Set up a scheduled job?
To set up a simple job in Python, use schedule
, a cron-like library. Here's a snippet that executes a function every day at 9AM.
This code schedules a job
to run on a daily basis. The infinite loop is our diligent task runner to execute pending tasks and rests in-between.
Go further: Django and management commands
For heavier projects using Django, centralize scheduled jobs by leveraging custom management commands.
Crafting your command
Start by creating a new command:
Then, mould the command:
Then, run it like python manage.py scheduler
.
Playing with advanced tools
Explore Celery for more complex scheduling requirements. It offers retry mechanisms, missed-task handling, and a plethora of execution options. Use django-cron or django-chronograph for a more Django-specific experience with admin interface perks. For Windows, consider using schtasks.exe
for scheduling (available from Windows 8 and Server 2012).
Keeping your commands in check
Refer to the latest Django documentation on writing custom management commands to foster good practices and ensure compatibility.
Choosing your armory
Your method of scheduling jobs will also depend on your deployment strategy. Keep in mind that cron
is a champion on POSIX systems, while Windows users can rally behind schtasks.exe
or the at
command.
Handling advanced scenarios
When basic schedule tasks don't fulfill your needs, you have more arrows in your quiver:
Recovering missed tasks
If a task should run following missed occurrences, study Celery beat. This tool reschedules if your server was off at the scheduled time.
Strange schedules
For irregular jobs, use the cron syntax. The python-crontab
library wraps this for you.
Bulky jobs & errors
Long-running and error-prone tasks benefit from Celery. It helps with smooth allocation of resources and error handling.
Managing dependencies
You want to preserve control and easy deployments. Relying on fewer external tools helps with this.
Dynamic scheduling
For schedules levers on database entries, review APScheduler. It stores schedules in your database for live alterations.
Was this article helpful?