⏰ Creating Repeating Tasks with schedule
and time
in Python
Want to automate tasks in Python, like sending reminders, checking the status of a website, or running a report at regular intervals? You can achieve this with the schedule
and time
modules.
In this tutorial, we’ll cover:
✅ Setting up repeating tasks with schedule
✅ Understanding how time.sleep()
works in automation
✅ Handling tasks that run indefinitely
✅ Practical examples of repetitive tasks
🧰 What You'll Need
-
Python 3.x
-
Basic knowledge of functions and loops
-
An idea for a task you want to automate at regular intervals
📦 Installing the schedule
Module
First, you need to install the schedule
module. It’s a lightweight Python package that makes it easy to schedule tasks.
To install it, run the following command:
pip install schedule
⏱️ Setting Up Repeating Tasks with schedule
The schedule
module allows you to easily set up repeating tasks at specific intervals like every minute, hour, or day.
1. Scheduling a Task to Run Every Minute
Here's how to run a task every minute using schedule
:
import schedule
import time
def task():
print("Task is running...")
# Schedule task to run every minute
schedule.every(1).minute.do(task)
while True:
schedule.run_pending()
time.sleep(1) # Wait 1 second between each check
Explanation:
-
schedule.every(1).minute.do(task)
: This schedules thetask()
function to run every minute. -
schedule.run_pending()
: This runs any tasks that are due to run. -
time.sleep(1)
: This adds a 1-second pause before checking again for tasks. This helps avoid overloading your CPU by checking too frequently.
2. Running Tasks Every Hour or Day
You can also schedule tasks to run on an hourly or daily basis.
# Run every hour
schedule.every().hour.do(task)
# Run every day at a specific time (e.g., 7:00 AM)
schedule.every().day.at("07:00").do(task)
🕒 Handling Repeating Tasks with time.sleep()
When using schedule
, you typically run an infinite loop to keep the scheduler checking for tasks that need to run. The time.sleep()
function helps prevent the script from using excessive CPU by pausing the execution for a brief time.
Here’s an example of how time.sleep()
works with repeating tasks:
import schedule
import time
def task():
print("The task is running...")
# Schedule a task to run every 5 seconds
schedule.every(5).seconds.do(task)
while True:
schedule.run_pending()
time.sleep(1) # Wait 1 second between checking for pending tasks
In this case:
-
The task is set to run every 5 seconds.
-
The
time.sleep(1)
pauses the program for 1 second between each task check, making the loop more efficient.
🔁 Handling Recurring Tasks
Sometimes, you might want to set up a task that repeats indefinitely at regular intervals, such as sending an email reminder or checking the system’s health.
Here’s how you can set up recurring tasks:
import schedule
import time
def check_system():
print("Checking system health...")
# Schedule to check system every 30 minutes
schedule.every(30).minutes.do(check_system)
# Repeat a task indefinitely
while True:
schedule.run_pending()
time.sleep(1)
This script will check the system health every 30 minutes and run indefinitely.
📈 Practical Examples of Repeating Tasks
Here are some practical examples of tasks you can automate:
1. Sending an Email Every Day at 8 AM
import schedule
import time
import smtplib
from email.mime.text import MIMEText
def send_email():
msg = MIMEText("This is your daily reminder!")
msg['Subject'] = "Daily Reminder"
msg['From'] = 'your_email@example.com'
msg['To'] = 'recipient_email@example.com'
with smtplib.SMTP('smtp.example.com') as server:
server.login('your_email@example.com', 'your_password')
server.sendmail('your_email@example.com', 'recipient_email@example.com', msg.as_string())
# Schedule to send email every day at 8 AM
schedule.every().day.at("08:00").do(send_email)
while True:
schedule.run_pending()
time.sleep(1)
2. Web Scraping Every Hour
import schedule
import time
import requests
from bs4 import BeautifulSoup
def scrape_website():
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.title.string)
# Scrape website every hour
schedule.every().hour.do(scrape_website)
while True:
schedule.run_pending()
time.sleep(1)
3. Backing Up Files Every Week
import schedule
import time
import shutil
def backup_files():
shutil.copy('source_file.txt', 'backup_directory')
# Schedule to run every week (on Mondays at 9 AM)
schedule.every().monday.at("09:00").do(backup_files)
while True:
schedule.run_pending()
time.sleep(1)
💡 Tips for Efficient Automation
-
Error Handling: Use
try-except
blocks to handle potential errors in your tasks.try: # task code except Exception as e: print(f"Error: {e}")
-
Logging: Implement logging to track the success and failure of each task.
import logging logging.basicConfig(filename='automation.log', level=logging.INFO) logging.info('Task started successfully.')
-
Task Prioritization: If you have multiple tasks, ensure they don’t interfere with each other by setting appropriate intervals or using separate threads.
🧠 Final Thoughts
The schedule
module makes it incredibly simple to run Python functions at regular intervals, whether it's every minute, hour, or day. Combined with time.sleep()
, this module is perfect for automating tasks such as sending emails, scraping websites, and backing up files.
By leveraging Python’s schedule
and time
modules, you can easily set up recurring tasks to save time and make your workflows more efficient.