Explain Codes LogoExplain Codes Logo

Set up a scheduled job?

python
management-commands
django-extensions
scheduling
Nikita BarsukovbyNikita Barsukov·Jan 16, 2025
TLDR

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.

import schedule import time def job(): # Do you want a coffee? print("Executing scheduled task... As regular as your morning coffee at 9AM") schedule.every().day.at("09:00").do(job) while True: schedule.run_pending() # Nap-time for 60 seconds, then coffee again! time.sleep(60)

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:

mkdir -p <your_app>/management/commands touch <your_app>/management/commands/scheduler.py

Then, mould the command:

from django.core.management.base import BaseCommand import schedule import time class Command(BaseCommand): help = 'Runs scheduled jobs... Just like your personal assistant would.' def handle(self, *args, **options): # Here is your digital barista def job(): self.stdout.write("Executing scheduled task... Espresso shot ready at 9AM") schedule.every().day.at("09:00").do(job) while True: # Barista on the watch! schedule.run_pending() # Shhh... Barista is on a break. time.sleep(60)

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.