Automate Everyday Tasks with Python and Schedule
Introduction
Python is a powerful language for scripting and automation. Combined with the schedule
library, you can easily run tasks at fixed intervals without needing cron jobs or complex background services. This tutorial walks you through using schedule
to build and run simple but useful automated scripts—from sending emails to backing up files or cleaning up directories.
Step 1 – Install the schedule Library
First, make sure you have Python 3 installed. Then install the schedule
library using pip
:
pip install schedule
The schedule
package is a lightweight job scheduler for Python that allows you to run functions at fixed times or intervals.
Step 2 – Create Your First Task
Here’s a basic script that prints a message every 10 seconds:
import schedule
import time
def job():
print("Running scheduled task...")
schedule.every(10).seconds.do(job)
while True:
schedule.run_pending()
time.sleep(1)
schedule.every(10).seconds.do(job) schedules the job
function to run every 10 seconds. The while
loop keeps checking for due tasks.
Step 3 – Schedule Daily or Weekly Jobs
You can schedule tasks for specific days and times. Here’s how to send a daily email at 9am:
def send_email():
print("Email sent!")
schedule.every().day.at("09:00").do(send_email)
To run tasks weekly:
schedule.every().monday.at("10:00").do(clean_temp_files)
Step 4 – Run Multiple Jobs
You can queue multiple jobs within the same script. Each can have different intervals:
schedule.every(5).seconds.do(job_one)
schedule.every().hour.do(job_two)
Make sure to keep calling schedule.run_pending()
inside a loop to execute due jobs.
Step 5 – Best Practices for Deployment
- Use
logging
instead ofprint()
for better debugging and output control - Consider wrapping the loop in a try-except block for resilience
- Use a process manager like
supervisord
orsystemd
to keep your script running
Conclusion
The schedule
library makes it easy to automate Python scripts without relying on external tools. Whether you want to send reminders, clean logs, or process data on a regular basis, this approach gives you control and flexibility with very little code.