AW Dev Rethought

Code is read far more often than it is written - Guido van Rossum

🧩 Python Automation Recipes – ⏱️ Scheduled Task Runner


Description:

📌 Introduction

Many automation scripts are useful only when they run at the right time.

Instead of relying on external cron jobs immediately, Python allows you to schedule tasks directly inside your code.

This automation recipe shows how to run Python scripts on a schedule using the lightweight schedule library — ideal for quick automations, prototypes, and long-running background tasks.


🔎 Explanation

  • The script uses the schedule library to define when tasks should run.
  • You can schedule jobs:
    • every few minutes
    • hourly
    • daily
    • at a specific time
  • A simple loop keeps the scheduler running and executes jobs when they’re due.

This pattern is commonly used for:

  • periodic cleanups
  • report generation
  • health checks
  • automation pipelines

✅ Key Takeaways

  • ⏱️ Schedule Python tasks with readable syntax.
  • 🔁 Ideal for recurring automations.
  • ⚙️ Simple alternative to cron for lightweight workflows.

Code Snippet:

import schedule
import time
from datetime import datetime

# --- Step 1: Define the task ---
def run_task():
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(f"🔁 Task executed at {now}")

# --- Step 2: Schedule the task ---
schedule.every(1).minutes.do(run_task)      # run every minute
# schedule.every().hour.do(run_task)
# schedule.every().day.at("10:00").do(run_task)

print("⏳ Scheduler started. Press Ctrl+C to stop.\n")

# --- Step 3: Run the scheduler loop ---
while True:
    schedule.run_pending()
    time.sleep(1)

Link copied!

Comments

Add Your Comment

Comment Added!