Setting up cron jobs in Python isn’t just about using time.sleep()
or writing bash scripts. With APScheduler, a powerful and flexible Python library, you can schedule and manage tasks directly in your codebase like a pro.
Why Use APScheduler?
APScheduler lets you run background jobs using different types of schedulers—like cron-style, interval-based, or date-based jobs. It supports persistent job stores and integrates cleanly with web frameworks.
Step 1: Install APScheduler
pip install apscheduler
Step 2: Basic Cron Job in Python
Here’s a simple example that mimics a traditional cron job:
from apscheduler.schedulers.blocking import BlockingScheduler
import datetime
def scheduled_job():
print("Job ran at", datetime.datetime.now())
scheduler = BlockingScheduler()
scheduler.add_job(scheduled_job, 'cron', hour=17, minute=30) # Runs every day at 17:30
scheduler.start()
Step 3: Using Interval Scheduling
If you want to run a task every few seconds or minutes:
scheduler.add_job(scheduled_job, 'interval', minutes=5)
Step 4: Graceful Shutdown
To handle shutdowns properly (important in production environments):
import signal
import sys
def shutdown(signum, frame):
scheduler.shutdown(wait=False)
sys.exit(0)
signal.signal(signal.SIGINT, shutdown)
signal.signal(signal.SIGTERM, shutdown)
Step 5: Running in Background (Optional)
Use `BackgroundScheduler` instead of `BlockingScheduler` if you're embedding the scheduler in an app (like Flask).
from apscheduler.schedulers.background import BackgroundScheduler
Conclusion
With APScheduler, cron jobs in Python become structured, testable, and reliable. Whether for periodic cleanup tasks or automated report generation, this tool gives you full control over your scheduled functions—without ever touching crontab.
If this post helped you, consider supporting me: buymeacoffee.com/hexshift