⏰ Python Tutorial — Task Scheduling (Automate Jobs on Time)
Introduction 🌟
Task Scheduling allows you to run Python scripts automatically at a specific time, repeatedly, or based on triggers. Python supports scheduling with built-in modules, third-party schedulers, OS-level schedulers, and cron-like job handling.
Note
💡 Schedule scripts daily, weekly, hourly
💡 Build automation bots & background services
💡 Useful for backups, reports, scraping, notifications
💡 Build automation bots & background services
💡 Useful for backups, reports, scraping, notifications
1. Scheduling with the schedule Library 🕒 (Simple & Beginner-Friendly)
install_schedule.sh
pip install scheduleBasic Example
schedule_basic.py
import schedule
import time
def job():
print("Running scheduled task!")
schedule.every(5).seconds.do(job)
while True:
schedule.run_pending()
time.sleep(1)✔ Runs a task every 5 seconds
More Schedules
schedule_various.py
schedule.every().minute.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("09:00").do(job)
schedule.every().monday.do(job)
schedule.every().sunday.at("18:30").do(job)2. Scheduling Multiple Jobs 🔁
multiple_jobs.py
def job1():
print("Job 1 executed")
def job2():
print("Job 2 executed")
schedule.every(2).seconds.do(job1)
schedule.every(5).seconds.do(job2)3. Passing Arguments to Scheduled Functions 🧩
args.py
def greet(name):
print("Hello", name)
schedule.every(10).seconds.do(greet, "Sathish")4. Scheduling with threading.Timer (One-Time Tasks) ⏳
timer.py
import threading
def task():
print("Task executed once!")
timer = threading.Timer(5, task)
timer.start()✔ Executes function after 5 seconds (only once)
5. Scheduling with APScheduler (Advanced) 🚀
install_apscheduler.sh
pip install apschedulerTypes of Schedulers
- ✔ BackgroundScheduler
- ✔ BlockingScheduler
- ✔ AsyncIOScheduler
- ✔ Tornado / Gevent schedulers
Cron-like Scheduling
apscheduler_cron.py
from apscheduler.schedulers.blocking import BlockingScheduler
scheduler = BlockingScheduler()
def job():
print("Cron Job Running...")
scheduler.add_job(job, "cron", hour=9, minute=0) # runs daily at 9:00 AM
scheduler.start()Interval Scheduling
apscheduler_interval.py
scheduler.add_job(job, "interval", seconds=10)Date-based Scheduling (One Time)
apscheduler_date.py
from datetime import datetime
scheduler.add_job(job, "date", run_date=datetime(2025, 5, 1, 10, 30))6. Running Python Scripts on Schedule (OS Level) 🖥️
🔹 Windows — Task Scheduler
- 1. Open Task Scheduler
- 2. Create Basic Task
- 3. Choose schedule (daily/weekly)
- 4. Set action → Start a Program
- 5. Choose python.exe and script path
🔹 Linux/macOS — Cron Jobs
cron_example.txt
crontab -eAdd a job:
Code Snippet
0 9 * * * /usr/bin/python3 /path/to/script.py✔ Runs daily at 9 AM
7. Real Automation Example — Daily Email Report 📬
email_report.py
import schedule, smtplib, time
from email.mime.text import MIMEText
def send_report():
msg = MIMEText("Daily Report!")
msg["Subject"] = "Report"
msg["From"] = "you@example.com"
msg["To"] = "team@example.com"
with smtplib.SMTP("smtp.gmail.com", 587) as server:
server.starttls()
server.login("you@example.com", "password")
server.send_message(msg)
schedule.every().day.at("09:00").do(send_report)
while True:
schedule.run_pending()
time.sleep(1)✔ Automatically emails your team daily
8. Scheduling a Web Scraper 🕸️
scraper_schedule.py
import schedule, time
import requests
from bs4 import BeautifulSoup
def scrape():
html = requests.get("https://quotes.toscrape.com").text
soup = BeautifulSoup(html, "html.parser")
print("Quote:", soup.find("span", class_="text").text)
schedule.every(30).minutes.do(scrape)
while True:
schedule.run_pending()
time.sleep(1)9. Running Background Tasks with Threads 🧵
background_thread.py
import schedule, threading, time
def worker():
while True:
schedule.run_pending()
time.sleep(1)
threading.Thread(target=worker, daemon=True).start()Task Scheduling Cheat Sheet 📘
| Library | Best Use |
|---|---|
| schedule | Simple lightweight jobs |
| threading.Timer | One-time delay tasks |
| APScheduler | Production-grade cron jobs |
| Cron (Linux) | Server-level automation |
| Task Scheduler (Windows) | Automated scripts in Windows |
Best Practices 💡
- ✔ Always log your scheduled jobs
- ✔ Use APScheduler for production
- ✔ Use Try/Except inside scheduled tasks
- ✔ Combine automation + scheduling for bots
- ✔ Ensure Python path is correct in cron jobs
Conclusion 🎉
>>“Scheduling turns automation into a reliable daily worker — Python makes it simple to run tasks exactly when you need them.” ✨
You now understand Task Scheduling in Python! Want the next topic? Try Background Workers, Celery Task Queues, APScheduler Advanced, or Automation Projects. Just tell me! 😊