🧩 Python Automation Recipes – 🔁 Retry Task Runner
Posted on: May 11, 2026
Description:
📌 Introduction
In real-world systems, tasks don’t always succeed on the first try — APIs fail, networks timeout, files get locked.
Instead of failing immediately, good systems retry tasks intelligently.
This automation recipe shows how to build a resilient task runner with:
- retries
- delay between attempts
- failure handling
This is a core pattern in production systems.
🔎 Explanation
- A task function is wrapped with retry logic.
- If it fails:
- it retries after a delay
- stops after max attempts
- You can plug this into:
- API calls
- file operations
- automation workflows
This introduces resilience, not just automation.
✅ Key Takeaways
- 🔁 Add retries to unstable operations.
- ⏱️ Use delays to avoid immediate repeated failures.
- 🧠 Build more reliable automation workflows.
Code Snippet:
import time
import random
from datetime import datetime
# --- Step 1: Define a sample unstable task ---
def unstable_task():
print("Running unstable task...")
# Simulate random failure
if random.random() < 0.7:
raise Exception("Simulated failure")
print("Task succeeded!")
# --- Step 2: Retry wrapper ---
def run_with_retry(task_func, max_retries=3, delay=2):
attempt = 0
while attempt < max_retries:
try:
print(f"\n▶Attempt {attempt + 1}")
task_func()
return True
except Exception as e:
print(f"Error: {e}")
attempt += 1
if attempt < max_retries:
print(f"Retrying in {delay} seconds...")
time.sleep(delay)
else:
print("Max retries reached. Task failed.")
return False
# --- Step 3: Execute task with retry ---
print(f"Starting task at {datetime.now()}\n")
run_with_retry(unstable_task, max_retries=5, delay=3)
print("\nExecution completed.")
Link copied!
Comments
Add Your Comment
Comment Added!
No comments yet. Be the first to comment!