How to Schedule Local Tasks Without Cron in Python
Run periodic tasks on a loop using the schedule library to mimic cron-like behavior from within Python.
pip install schedule
Python code
22 linesimport schedule
import time
from datetime import datetime
def greet():
print(f"Hello at {datetime.now().strftime('%H:%M:%S')}")
def check_time():
now = datetime.now()
print(f"Current time: {now:%H:%M:%S}")
schedule.every(5).seconds.do(greet)
schedule.every(10).seconds.do(check_time)
schedule.every(1).minute.do(lambda: print("One minute has passed"))
if __name__ == "__main__":
print("Task scheduler started (runs for 30 seconds)...")
end_time = time.time() + 30
while time.time() < end_time:
schedule.run_pending()
time.sleep(1)
print("Scheduler stopped.")
Output
Task scheduler started (runs for 30 seconds)...
Hello at 14:23:05
Current time: 14:23:10
Hello at 14:23:10
Current time: 14:23:15
Hello at 14:23:15
One minute has passed
Hello at 14:23:20
Current time: 14:23:25
Hello at 14:23:25
Hello at 14:23:30
Current time: 14:23:30
Hello at 14:23:35
Scheduler stopped.
How it works
The schedule library provides a human-friendly syntax for defining recurring jobs without shell cron. schedule.every(5).seconds.do(greet) registers greet to run every 5 seconds. The main loop calls schedule.run_pending() to execute any jobs whose scheduled time has passed, then sleeps 1 second to avoid busy waiting. Each job runs its Python function in the same thread, so long-running tasks will block others unless you add threading.
Common mistakes
- Forgetting to call `schedule.run_pending()` in the loop — jobs are defined but never executed.
- Using blocking sleep inside a job and delaying the scheduler loop.
- Omitting `time.sleep(1)` — without it, the loop hogs CPU by calling `run_pending` thousands of times per second.
- Assuming jobs run exactly on the second — `schedule` checks the clock every iteration, so a 5-second job may drift if other jobs take time.
Variations
- Use `schedule.every().day.at("10:30").do(task)` for daily one-time jobs.
- Wrap the loop in a daemon thread to run scheduled jobs alongside an interactive program.
Real-world use cases
- Running a periodic health check on a local database or API endpoint and logging results.
- Cleaning up temporary files in a downloads folder every hour during development.
- Sending a reminder notification or email at a fixed time each day from a desktop application.
Sponsored
More from Automation & scripting
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
- Automatically Log CPU, RAM, and Disk Usage Every Minute in Python easy
- Batch Rename Hundreds of Files in Python easy
Keep learning
Related tutorials and quizzes for this topic.