If you’re used to setting up cron jobs on Linux to automate tasks, but want a simple, Python-native way to schedule jobs, the schedule library is an excellent alternative. It allows you to run Python functions periodically without relying on system-level cron.
In this post, I’ll show you how to:
- Install and use the
schedulelibrary - Write Python scripts that run tasks on a schedule
- Keep your jobs running continuously
- Understand when to use
scheduleinstead of cron
What Is the schedule Library?
schedule is a lightweight Python package designed to run jobs periodically inside your Python program. Unlike cron, which is managed by your OS, schedule lets you embed scheduling logic directly in Python.
This makes it ideal for cross-platform automation and when you want to keep everything in Python.
Installation
Install it easily with pip:
pip install schedule
Basic Usage Example
Here’s a simple example that prints the current time every minute:
import schedule
import time
from datetime import datetime
def job():
print(f"Task running at {datetime.now()}")
# Schedule the job every minute
schedule.every(1).minutes.do(job)
print("Scheduler started. Press Ctrl+C to exit.")
while True:
schedule.run_pending()
time.sleep(1)
This script:
- Defines a
jobfunction to run on schedule - Schedules it every minute
- Enters an infinite loop that checks and runs due jobs
Scheduling Variations
schedule supports many common patterns:
schedule.every().day.at("14:00").do(job) # Every day at 2 PM
schedule.every().hour.do(job) # Every hour
schedule.every().monday.do(job) # Every Monday
schedule.every(10).seconds.do(job) # Every 10 seconds
schedule.every(5).to(10).minutes.do(job) # Every 5 to 10 minutes (random)
Keeping Your Scheduled Jobs Running
Since schedule runs within your Python script, you need to ensure the script stays alive:
- Run inside a terminal multiplexer like
screenortmux - Use Linux tools like
systemdorsupervisordto manage the script - Run as a background process with
nohupor& - Dockerize your script with restart policies for resilience
Why Use schedule Over Cron?
- Cross-platform: Works on Linux, macOS, Windows without changes
- Python-native: Write schedules in Python rather than shell scripts
- Dynamic: Modify schedules programmatically at runtime
- Single process: Manage multiple jobs from one Python app
Limitations Compared to Cron
- The Python script must be continuously running for tasks to execute
- Lacks built-in logging, notifications, or advanced cron features
- Not suitable for system-level task scheduling where OS guarantees execution
When Should You Use schedule?
- When you want to keep all logic inside Python
- For cross-platform automation without OS dependencies
- When you want simple scheduling integrated with your Python app
For mission-critical or system-level tasks, traditional cron combined with Python scripts is still recommended.
Helpful links:
Top comments (0)