Sub topic 10
Running Workflows on a Schedule or a Trigger
This chapter assumes you have a workflow with fixed inputs, templated prompts, validated outputs, and a human review step. It also assumes you can read short Python snippets. Here you will decide when a workflow should run, and how to keep an unattended run safe.
Two ways to start a run
A workflow starts in one of two ways.
- A schedule starts it at a set time, such as every Monday at 08:00. Weekly newsletters, monthly reports, and recurring social posts fit this pattern.
- A trigger starts it when something happens, such as a new row in a campaign sheet, a blog post marked "published", or a form submission.
Pick a schedule when the task follows the calendar. Pick a trigger when the task follows an event, or when the input only exists after something else finishes.
| Question | Schedule | Trigger |
|---|---|---|
| What starts the run? | The clock | An event |
| Typical task | Weekly digest, monthly report | Post a summary when an article is published |
| Main risk | Running when inputs are stale or missing | Running twice for one event |
| Check before running | Are today's inputs present? | Have I handled this event already? |
The run function stays the same
Keep the workflow itself separate from whatever starts it. A schedule, a trigger, and a manual run should all call the same function. That way you test one path, and a change to the workflow applies everywhere.
def run_once(inputs, steps, call_model, run_workflow):
"""Entry point used by the scheduler, a trigger, or a person."""
return run_workflow(inputs, steps, call_model)Here run_workflow is the function from the chaining chapter. The scheduler only decides when run_once is called.
Scheduling with cron
Cron is a scheduler built into Linux and macOS. A cron expression has five fields: minute, hour, day of month, month, and day of week.
0 8 * * 1 /usr/bin/python3 /opt/workflows/weekly_newsletter.pyThis runs the script every Monday at 08:00 in the server's time zone. Check that time zone. A run set for 08:00 on a server in UTC fires at a different local hour than your audience expects, and the offset changes with daylight saving time. Hosted tools such as GitHub Actions, cloud schedulers, and automation platforms offer the same idea with their own syntax.
Making triggered runs safe
Triggers often fire more than once for the same event. A webhook can be retried when the first delivery looks slow. A spreadsheet can report the same row as changed twice. If your workflow sends or posts something, a duplicate run is a visible mistake.
The fix is to make the run idempotent, which means running it twice for the same event has the same effect as running it once. The simplest method is to record the ID of each handled event.
import json
from pathlib import Path
SEEN_FILE = Path("seen_events.json")
def already_handled(event_id):
if not SEEN_FILE.exists():
return False
return event_id in json.loads(SEEN_FILE.read_text())
def mark_handled(event_id):
seen = json.loads(SEEN_FILE.read_text()) if SEEN_FILE.exists() else []
seen.append(event_id)
SEEN_FILE.write_text(json.dumps(seen))
def handle_event(event, run_workflow_for):
if already_handled(event["id"]):
return "skipped: already handled"
result = run_workflow_for(event)
mark_handled(event["id"])
return resultThe event is marked as handled only after the run succeeds, so a failed run can be retried. A shared database is better than a local file when more than one machine can receive events.
Guardrails for unattended runs
Nobody watches a scheduled run, so build the checks into it.
- Check inputs first. If the brief or data export is empty or older than expected, stop and notify someone. Do not let the model fill the gap with invented content.
- Keep the review checkpoint. An automatic run should produce a draft and place it in a review queue. It should not publish. Remove review only for low-risk outputs, and only after evaluation results support it.
- Validate outputs. Reuse your structured-output checks. A failed validation ends the run with an alert.
- Limit retries and volume. Allow two or three retries, and cap how many items one run can produce. This prevents a loop from sending hundreds of messages or running up model costs.
- Log every run. Record the start time, the trigger, the workflow version, the inputs used, and the outcome. These logs are what you read when a draft looks wrong.
Common errors
- Wrong time zone. The job runs at an unexpected local hour.
- Duplicate events. The same webhook triggers two posts.
- Silent failure. The job fails and nobody is told, so the newsletter is simply missing. Always send an alert on failure.
- Stale inputs. The job runs before the data export is ready. Check a timestamp, or trigger from the export finishing instead of using a clock.
Exercise
Your workflow posts a summary to Slack whenever a new blog post is published, and a retried webhook caused the summary to be posted twice. What change prevents this, and where in the run should it happen?
Show answer
Make the run idempotent. Before running, look up the event's ID in a record of handled events and skip the run if it is already there. After the run succeeds, add the ID to the record. Marking it only after success lets a failed run be retried while still blocking duplicates.