Schedule Daily Task in Python
Use the schedule library to queue a daily task at a fixed time, then simulate a loop that checks for pending jobs.
pip install schedule
Python code
13 linesimport schedule
import time
from datetime import datetime
def daily_task():
print(f"Task executed at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
schedule.every().day.at("10:30").do(daily_task)
if __name__ == "__main__":
for _ in range(3):
schedule.run_pending()
time.sleep(1)
Output
(no output, since the job is scheduled for 10:30 and the loop runs without triggering it; the script exits silently.)
How it works
The schedule.every().day.at("10:30") call registers a daily job that calls daily_task when the time matches. In the mock loop, schedule.run_pending() checks if any scheduled jobs are due and runs them; since the loop runs at a different time, nothing triggers. The time.sleep(1) pauses execution to simulate a simple polling loop. This pattern shows how to schedule jobs and test them without waiting for the actual time.
Common mistakes
- Not calling `schedule.run_pending()` inside an infinite loop, so jobs never execute.
- Misunderstanding `at()` time format – it must be a 24-hour HH:MM string.
- Forgetting that `run_pending()` only runs jobs that are due, not all jobs.
- Using `time.sleep()` too aggressively, which can block other tasks.
Variations
- Replace the fixed loop with `while True: schedule.run_pending(); time.sleep(1)` for a real scheduler.
- Use `schedule.every().day.at("10:30").do(lambda: print("Task"))` for a simple one-liner.
Real-world use cases
- Running daily database backups at a fixed hour with a lightweight Python script.
- Sending a scheduled report email to stakeholders every morning at 9 AM.
- Triggering a data sync job between services at a specific time each day.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- 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
Keep learning
Related tutorials and quizzes for this topic.