Learn how to automate LLM jobs so they run without you — on a schedule, in response to events, or via background task queues. This lesson covers cron, APScheduler, Celery with Redis, file watchers, and webhook handlers with real, production-ready Python code.

Imagine you've built a beautiful LLM-powered pipeline that summarizes customer support tickets and flags urgent issues. It works perfectly when you run it manually from your terminal. But your users need those summaries waiting in their inbox every morning. The tickets keep arriving overnight. Nobody wants to wake up at 3 AM to run a Python script.
This is the gap between a working prototype and a production system: automation. Almost every real-world LLM application eventually needs to run jobs on a schedule, respond to events, or process work from a queue rather than running interactively. A news digest system needs to fire at 6 AM every day. A document ingestion pipeline needs to kick off when a new file lands in cloud storage. A batch classification job needs to process thousands of items without overwhelming your API rate limits or crashing your server.
By the end of this lesson, you'll know how to wire up your LLM jobs to actually run themselves — on time, reliably, and at scale. You'll understand the right tool for each scenario and have working code you can drop into real projects.
What you'll learn:
You should be comfortable writing Python and have worked with at least one LLM API before. If you haven't yet, check out Using the OpenAI API with Python or Building Your First AI App with the Claude API to get your footing. You'll also want Python 3.9+, Redis installed locally (or via Docker), and a valid API key for whichever LLM you're using.
Before we write any code, let's build a mental model. There are three fundamental ways to trigger automated work:
Cron / scheduled execution — "Run this job at a specific time, repeatedly." Think of it like setting an alarm clock. It fires whether or not anything interesting has happened in the world. Best for: daily digests, weekly reports, nightly batch processing.
Task queues — "Here's a unit of work; a worker should pick it up and execute it." Think of it like a to-do list that gets handed to available workers. The submitter doesn't wait around. Best for: processing user uploads, handling webhooks, parallelizing large batch jobs.
Event-driven pipelines — "When X happens, do Y." Think of it like setting a trigger on a mousetrap. The system reacts to something changing in the environment. Best for: real-time document ingestion, responding to database changes, reacting to user actions.
These patterns aren't mutually exclusive. A sophisticated system often combines all three: a cron job checks for new files, publishes tasks to a queue, and each worker processes one document and fires an event when it's done.
Key insight
The pattern you choose isn't about preference — it's about what initiates the work. Time → cron. User action or upstream system → queue. Data change or system event → event-driven. Get this classification right and everything else follows naturally.
Cron is a Unix utility that runs commands on a schedule defined by a simple syntax. The schedule is a five-field expression describing minute, hour, day-of-month, month, and day-of-week:
┌───────────── minute (0–59)
│ ┌─────────── hour (0–23)
│ │ ┌───────── day of month (1–31)
│ │ │ ┌─────── month (1–12)
│ │ │ │ ┌───── day of week (0–7, 0=Sunday)
│ │ │ │ │
* * * * * command_to_execute
Some useful examples:
0 6 * * * — Every day at 6:00 AM0 9 * * 1 — Every Monday at 9:00 AM*/15 * * * * — Every 15 minutes0 2 1 * * — First day of every month at 2:00 AMLet's build a real example: a daily summarizer that pulls the last 24 hours of customer support tickets from a SQLite database, generates a summary with an LLM, and saves it to a file.
First, the Python script (daily_support_digest.py):
import sqlite3
import json
import os
from datetime import datetime, timedelta
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
def fetch_todays_tickets(db_path: str) -> list[dict]:
"""Fetch support tickets from the last 24 hours."""
cutoff = (datetime.now() - timedelta(hours=24)).isoformat()
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute(
"SELECT id, subject, body, created_at FROM tickets WHERE created_at > ?",
(cutoff,)
)
rows = cursor.fetchall()
conn.close()
return [
{"id": row[0], "subject": row[1], "body": row[2], "created_at": row[3]}
for row in rows
]
def generate_digest(tickets: list[dict]) -> str:
"""Send tickets to the LLM and get a structured daily digest."""
if not tickets:
return "No support tickets received in the last 24 hours."
ticket_text = "\n\n".join(
f"Ticket #{t['id']} ({t['created_at']})\nSubject: {t['subject']}\n{t['body']}"
for t in tickets
)
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": (
"You are a customer support analyst. Given a list of support tickets, "
"produce a concise daily digest that includes: (1) total ticket count, "
"(2) top 3 recurring issues, (3) any tickets that appear urgent or escalated, "
"(4) overall sentiment trend. Be specific and actionable."
)
},
{
"role": "user",
"content": f"Here are today's support tickets:\n\n{ticket_text}"
}
],
max_tokens=800
)
return response.choices[0].message.content
def save_digest(digest: str, output_dir: str) -> str:
"""Save the digest to a dated file."""
os.makedirs(output_dir, exist_ok=True)
today = datetime.now().strftime("%Y-%m-%d")
output_path = os.path.join(output_dir, f"digest_{today}.txt")
with open(output_path, "w") as f:
f.write(f"Support Digest — {today}\n")
f.write("=" * 40 + "\n\n")
f.write(digest)
return output_path
if __name__ == "__main__":
DB_PATH = "/var/data/support.db"
OUTPUT_DIR = "/var/reports/digests"
print(f"[{datetime.now().isoformat()}] Starting daily support digest...")
tickets = fetch_todays_tickets(DB_PATH)
print(f"Fetched {len(tickets)} tickets.")
digest = generate_digest(tickets)
output_path = save_digest(digest, OUTPUT_DIR)
print(f"Digest saved to {output_path}")
Now register this with cron. Run crontab -e to open your cron file, and add:
0 6 * * * /usr/bin/python3 /home/youruser/scripts/daily_support_digest.py >> /var/log/digest.log 2>&1
That >> /var/log/digest.log 2>&1 part is critical — it redirects both stdout and stderr to a log file. Without it, errors vanish silently into the void, which is how cron jobs earn their reputation for being mysterious.
Warning
Cron runs in a minimal environment. It won't have your .bashrc loaded, so environment variables like OPENAI_API_KEY won't be set. Either hardcode the full path to a .env file in your script, use a tool like python-dotenv, or export variables at the top of your crontab file with OPENAI_API_KEY=sk-....
If you'd rather not touch cron files, APScheduler lets you define schedules in pure Python and run them inside your application:
from apscheduler.schedulers.blocking import BlockingScheduler
from daily_support_digest import fetch_todays_tickets, generate_digest, save_digest
scheduler = BlockingScheduler()
@scheduler.scheduled_job('cron', hour=6, minute=0)
def run_daily_digest():
print("APScheduler firing daily digest job...")
tickets = fetch_todays_tickets("/var/data/support.db")
digest = generate_digest(tickets)
save_digest(digest, "/var/reports/digests")
print("Daily digest complete.")
scheduler.start()
APScheduler is especially useful when you're deploying to platforms like Heroku or Railway where you can't edit a crontab, or when your schedule needs to be configurable at runtime.
Imagine a user uploads a 50-page PDF and your system needs to chunk it, generate embeddings, and produce a summary. If you do all that work synchronously in the HTTP request handler, the user's browser is sitting there with a spinner for 30+ seconds. Worse, if the request times out, you've wasted all that work.
Task queues solve this by separating the producer (the code that says "do this work") from the worker (the code that actually does it). Your web server receives the upload, drops a task into the queue, and immediately returns a "processing" response to the user. Workers running separately pick up the task and process it in the background.
Note
Redis here acts as the message broker — the shared bulletin board that producers write to and workers read from. The tasks themselves are serialized to JSON and stored in Redis until a worker picks them up.
Install the dependencies:
pip install celery redis openai
Start Redis (if you have Docker):
docker run -d -p 6379:6379 redis:alpine
Create tasks.py:
import os
from celery import Celery
from openai import OpenAI
import time
# Configure Celery to use Redis as the broker and result backend
app = Celery(
"llm_jobs",
broker="redis://localhost:6379/0",
backend="redis://localhost:6379/1"
)
# Optional: configure task behavior globally
app.conf.update(
task_serializer="json",
result_expires=3600, # Results stay in Redis for 1 hour
task_acks_late=True, # Only acknowledge after successful completion
worker_prefetch_multiplier=1 # Workers grab one task at a time (safe for slow LLM calls)
)
openai_client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
@app.task(
bind=True,
max_retries=3,
default_retry_delay=60 # Wait 60 seconds before retrying
)
def summarize_document(self, document_id: int, text: str) -> dict:
"""
Celery task: summarize a document with an LLM.
Returns a dict with the document_id and summary.
"""
try:
response = openai_client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": "Summarize the following document in 3-5 sentences. Focus on key facts and conclusions."
},
{"role": "user", "content": text}
],
max_tokens=300
)
summary = response.choices[0].message.content
return {"document_id": document_id, "summary": summary, "status": "success"}
except Exception as exc:
# This catches rate limits, timeouts, network errors, etc.
# Celery will retry according to max_retries and default_retry_delay
raise self.retry(exc=exc)
@app.task(bind=True, max_retries=3, default_retry_delay=120)
def classify_support_ticket(self, ticket_id: int, subject: str, body: str) -> dict:
"""Classify a support ticket by category and urgency."""
try:
response = openai_client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{
"role": "system",
"content": (
"Classify the support ticket. Return JSON with these fields: "
"category (billing|technical|account|other), "
"urgency (low|medium|high|critical), "
"one_line_summary (string). "
"Return only valid JSON, no extra text."
)
},
{
"role": "user",
"content": f"Subject: {subject}\n\n{body}"
}
],
max_tokens=150
)
import json
result = json.loads(response.choices[0].message.content)
result["ticket_id"] = ticket_id
return result
except Exception as exc:
raise self.retry(exc=exc)
Tip
Setting worker_prefetch_multiplier=1 is especially important for LLM tasks. Without it, Celery workers grab multiple tasks upfront. If each task takes 5-10 seconds (realistic for LLM calls), workers hoard tasks they haven't started yet, starving other workers and making rate limit management unpredictable.
# producer.py — this runs in your web server, CLI, or another script
from tasks import summarize_document, classify_support_ticket
# Submit a document summarization job
# .delay() sends the task to the queue immediately
job = summarize_document.delay(
document_id=1042,
text="Acme Corp's Q3 revenue fell 12% year-over-year, primarily driven by..."
)
print(f"Task submitted. ID: {job.id}")
# Later, check if it's done (non-blocking)
if job.ready():
result = job.result
print(f"Document {result['document_id']} summary: {result['summary']}")
else:
print("Still processing...")
# Or wait for it (blocking — useful in batch scripts, not web handlers)
result = job.get(timeout=30)
print(result)
Start a worker in a separate terminal:
celery -A tasks worker --loglevel=info --concurrency=4
The --concurrency=4 flag means 4 worker processes running in parallel. For LLM tasks that are mostly waiting on network I/O, you can often push this higher. For GPU-bound local models, keep it at 1.
One of Celery's most powerful features is chaining tasks together. Say you want to classify a ticket and then summarize it only if it's high priority:
from celery import chain
from tasks import classify_support_ticket, summarize_document
# This chains won't work directly since the output shapes differ,
# but here's the pattern — in practice you'd write a linking task:
@app.task
def summarize_if_urgent(classification: dict, full_body: str) -> dict:
"""Only summarize tickets classified as high or critical urgency."""
if classification["urgency"] in ("high", "critical"):
summary_job = summarize_document.delay(
document_id=classification["ticket_id"],
text=full_body
)
classification["summary_task_id"] = summary_job.id
classification["flagged_for_review"] = classification["urgency"] == "critical"
return classification
For handling complex LLM workflows with multiple steps, retries, and branching logic, also check out the patterns covered in Agentic Loop Design: Building Reliable Multi-Step LLM Pipelines.
Event-driven systems react to things that happen rather than waiting for a clock or a human. A file appears in an S3 bucket, a row gets inserted into a database, a webhook fires from Stripe — your pipeline wakes up and responds.
Python's watchdog library lets you monitor the filesystem for changes. This is a simple but surprisingly powerful pattern for local or server-based document pipelines:
# file_watcher.py — watches a directory and triggers LLM processing on new files
import time
import os
from pathlib import Path
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from tasks import summarize_document # Our Celery task from earlier
class DocumentDropHandler(FileSystemEventHandler):
"""
Triggered whenever a file is created in the watched directory.
Submits it to the Celery queue for LLM processing.
"""
SUPPORTED_EXTENSIONS = {".txt", ".md"}
def on_created(self, event):
if event.is_directory:
return
path = Path(event.src_path)
if path.suffix.lower() not in self.SUPPORTED_EXTENSIONS:
print(f"Ignoring unsupported file type: {path.name}")
return
print(f"New file detected: {path.name}. Submitting to queue...")
# Read the file contents
try:
text = path.read_text(encoding="utf-8")
except Exception as e:
print(f"Could not read {path.name}: {e}")
return
# Submit to Celery — the watcher doesn't wait for the result
job = summarize_document.delay(
document_id=hash(path.name), # Use filename hash as a simple ID
text=text
)
print(f"Task {job.id} submitted for {path.name}")
if __name__ == "__main__":
WATCH_DIRECTORY = "/var/data/incoming_documents"
os.makedirs(WATCH_DIRECTORY, exist_ok=True)
event_handler = DocumentDropHandler()
observer = Observer()
observer.schedule(event_handler, path=WATCH_DIRECTORY, recursive=False)
observer.start()
print(f"Watching {WATCH_DIRECTORY} for new documents. Press Ctrl+C to stop.")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
This pattern is at the heart of Building a Production Document Q&A System with Vector Embeddings — files land somewhere, trigger ingestion, and get indexed automatically.
A very common real-world pattern is using webhooks. A third-party service (Stripe, GitHub, Intercom) sends an HTTP POST to your server when something happens, and you kick off an LLM job in response.
# webhook_handler.py — a simple Flask endpoint that receives webhooks
# and submits Celery tasks
from flask import Flask, request, jsonify
import hmac
import hashlib
from tasks import classify_support_ticket
app = Flask(__name__)
WEBHOOK_SECRET = os.environ["INTERCOM_WEBHOOK_SECRET"]
def verify_signature(payload: bytes, signature: str) -> bool:
"""Verify that the webhook actually came from Intercom."""
expected = hmac.new(
WEBHOOK_SECRET.encode(),
payload,
hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, signature)
@app.route("/webhooks/new-ticket", methods=["POST"])
def handle_new_ticket():
# Verify the request is authentic
signature = request.headers.get("X-Hub-Signature-256", "")
if not verify_signature(request.data, signature):
return jsonify({"error": "Invalid signature"}), 401
payload = request.json
ticket = payload.get("data", {}).get("item", {})
# Submit to Celery — respond immediately, process in background
job = classify_support_ticket.delay(
ticket_id=ticket.get("id"),
subject=ticket.get("title", "No subject"),
body=ticket.get("body", "")
)
# Return 200 fast — webhook providers retry if they don't hear back quickly
return jsonify({"status": "accepted", "task_id": job.id}), 202
if __name__ == "__main__":
app.run(port=5000)
Warning
Webhook endpoints must respond within a few seconds or the sender will retry the request. This is exactly why you drop the work into a queue and return immediately — never do the LLM processing synchronously inside a webhook handler.
Automated LLM jobs run without anyone watching. When they fail, they fail silently — unless you build failure handling in from the start.
The most common failure mode in production is hitting API rate limits. When you're processing 500 tickets in a batch job, you'll almost certainly hit your tokens-per-minute limit. The right response is exponential backoff: wait a bit, try again, wait longer if it fails again.
import time
import random
from openai import RateLimitError, APITimeoutError
def call_llm_with_backoff(client, messages, max_retries=5, base_delay=1.0):
"""
Call the LLM API with exponential backoff for rate limit errors.
"""
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
max_tokens=500
)
return response.choices[0].message.content
except RateLimitError:
if attempt == max_retries - 1:
raise # Give up after max retries
# Exponential backoff with jitter
delay = base_delay * (2 ** attempt) + random.uniform(0, 1)
print(f"Rate limited. Waiting {delay:.1f}s before retry {attempt + 1}...")
time.sleep(delay)
except APITimeoutError:
if attempt == max_retries - 1:
raise
delay = base_delay * (2 ** attempt)
print(f"Timeout. Retrying in {delay:.1f}s...")
time.sleep(delay)
This connects directly to the deeper patterns described in Handling LLM Errors, Timeouts, and Rate Limits in Python Applications.
Also consider Cost Optimization: Token Counting, Caching, and Model Selection for LLMs before running large batch jobs — a misconfigured automated job hitting an expensive model repeatedly is a great way to generate a surprising API bill.
| Scenario | Best Pattern |
|---|---|
| Generate weekly email reports | Cron |
| Nightly re-embedding of updated documents | Cron |
| Process a user's uploaded PDF | Task queue |
| Classify incoming webhook events | Task queue + webhook handler |
| Index new files dropped in a folder | Event-driven (file watcher) |
| Respond to a database row insertion | Event-driven (DB trigger / CDC) |
| Run a 10,000-document batch classification | Task queue with rate-limited workers |
Build a mini automated pipeline that combines all three patterns:
Set up a cron job (or APScheduler) that runs every 5 minutes and checks a SQLite database for unprocessed articles (rows where processed = 0).
For each unprocessed article, submit a Celery task that calls an LLM to generate a one-sentence headline and a category (use the classify_support_ticket pattern from above, adapted for articles).
In the Celery task, write the result back to the database (update the row with the generated headline, category, and set processed = 1).
Add a file watcher using watchdog that monitors an incoming/ directory. When a .txt file appears, insert it into the SQLite database as a new unprocessed article.
Expected flow: You drop a .txt file into incoming/ → file watcher inserts it into the database → cron job picks it up within 5 minutes → Celery worker processes it with an LLM → results land back in the database.
This exercise forces you to handle the handoff points between all three patterns, which is where most real production bugs live.
"My cron job works in the terminal but not when cron runs it."
Almost always an environment variable problem. Add echo $PATH and printenv to a test cron job and check the log. Use absolute paths for everything: your Python interpreter, your script, your data files.
"Tasks pile up in my queue and workers can't keep up."
You have more producers than your workers can handle. First, check whether the bottleneck is your LLM API rate limits (use celery inspect active to see what workers are doing). If you're being rate-limited, reduce concurrency. If workers are genuinely overwhelmed, scale horizontally by running more worker processes.
"Celery tasks run once and then never again."
Make sure Redis is running and your broker URL is correct. Run celery -A tasks inspect ping to verify workers are alive. Check that your task was actually submitted by logging the task ID when you call .delay().
"My file watcher triggers multiple times for one file."
Some file editors and copy tools write files in stages, causing multiple on_created events. Add a short time.sleep(0.5) before reading the file, or check that the file size is stable across two reads before submitting the task.
"My automated job ran out of context window." When batching items for LLM processing in automated jobs, you must track token counts. Shoving all 500 tickets into one prompt will exceed the context limit. See Understanding Tokens: How LLMs Tokenize Text and Why It Affects Your Inputs, Outputs, and Costs for how to count before you send.
Tip
Add structured logging with timestamps to every automated LLM job. When something fails at 3 AM, your log file is the only witness. Use Python's logging module with %(asctime)s in your format string, and log at the start and end of each major step.
You've now got a solid foundation for automating LLM jobs in production. Here's the mental model to carry forward:
task_acks_late=True and worker_prefetch_multiplier=1 for LLM tasks, always implement retries.The patterns you've learned here become even more powerful when you add observability. Once your jobs are running automatically, you need visibility into what's succeeding, what's failing, and how long things are taking. That's the domain of Implementing LLM Observability: Tracing, Logging, and Monitoring Requests in Production.
You should also think about structured outputs in your automated pipelines — when no human is watching the output, getting back reliable JSON rather than freeform text becomes essential. Structured Output: Getting JSON, Tables, and Code from LLMs covers exactly that.
Finally, if you need to run many LLM jobs in parallel to meet throughput targets, Orchestrating Parallel LLM Calls: Batching, Concurrency, and Async Patterns for High-Throughput Production Pipelines is your next stop.
Your pipelines are now capable of running without you. Use that power wisely — and always check your logs in the morning.
Building with LLMs