Sub topic 10
Running workflows on a schedule or a trigger
This chapter assumes you have a workflow that already runs by hand: a template, a validated structured output, and a chain of steps like the ones in earlier chapters. You should also be able to read short Python snippets. The goal here is to run that workflow without someone pressing the button, and to do it safely.
Why automatic runs change the risk
A workflow you start by hand has a person watching. If the output looks wrong, you stop. A workflow that starts on its own has no one watching at the moment it runs. That makes three things more important:
- Inputs must be gathered automatically. The workflow cannot ask you to paste in the brief.
- Failures must be visible. A silent failure on a Monday morning means no newsletter and nobody knows why.
- Repeats must be harmless. Schedulers and event systems sometimes run the same job twice.
Automation does not remove human review. It moves it. A scheduled workflow should usually produce a draft and notify a person, not publish by itself.
Two ways to start a run
A schedule starts a run at a fixed time, such as every Monday at 08:00. A trigger starts a run when an event happens, such as a new row in a spreadsheet, a form submission, or a published blog post.
| Aspect | Schedule | Trigger |
|---|---|---|
| Starts when | The clock reaches a set time | An event occurs |
| Typical tasks | Weekly newsletter, monthly report | Post-publish social copy, lead follow-up |
| Input source | Data pulled at run time | Data carried by the event |
| Main risk | Stale or missing data at run time | Duplicate or burst events |
| Volume | Predictable | Can spike |
Choose a schedule when the work has a natural rhythm and needs data that accumulates, like last week's results. Choose a trigger when the work responds to something specific and delay has a cost. Many teams combine them: a trigger creates a draft when a post is published, and a weekly schedule collects the drafts into a digest.
Reading a cron expression
Most schedulers accept cron expressions. A cron expression is a line of five fields that describes when to run. The fields are minute, hour, day of month, month, and day of week.
| Expression | Meaning |
|---|---|
| `0 8 * * 1` | 08:00 every Monday |
| `30 6 1 * *` | 06:30 on the first day of each month |
| `0 9 * * 1-5` | 09:00 on weekdays |
| `*/15 * * * *` | Every 15 minutes |
An asterisk means "every value". Day of week uses 0 or 7 for Sunday in most implementations, so check your tool's documentation.
Two details cause most scheduling mistakes:
- Time zones. Many cloud schedulers run in UTC unless you set a zone. A job set for 08:00 may run at 03:00 local time, or move by an hour when daylight saving changes. Set the zone explicitly where the tool allows it.
- Run time versus data time. If a report covers "last week", compute that range from the run date inside the workflow. Do not hard-code dates in the template.
Make the run self-contained
A scheduled run needs everything it uses to be either stored or fetchable. Write a small entry function that builds the inputs, runs the workflow, validates the result, and saves a draft. The example below reuses run_workflow from the chaining chapter and keeps its dependencies passed in as arguments, so you can test it with fakes.
from datetime import date, timedelta
import json
def last_week_range(today):
"""Return the Monday and Sunday of the previous full week."""
this_monday = today - timedelta(days=today.weekday())
start = this_monday - timedelta(days=7)
end = start + timedelta(days=6)
return start, end
def run_workflow(inputs, steps, call_model):
context = dict(inputs)
for step in steps:
prompt = step["template"].format(**context)
context[step["output"]] = call_model(prompt)
return context
STEPS = [
{
"template": (
"Summarize these results for {week_start} to {week_end} "
"in 3 bullets:\n{metrics}"
),
"output": "summary",
},
{
"template": (
"Return JSON with keys subject, preview_text, body for a "
"newsletter based on:\n{summary}"
),
"output": "draft_json",
},
]
def scheduled_newsletter(today, fetch_metrics, call_model, save_draft):
start, end = last_week_range(today)
inputs = {
"week_start": start.isoformat(),
"week_end": end.isoformat(),
"metrics": fetch_metrics(start, end),
}
context = run_workflow(inputs, STEPS, call_model)
draft = json.loads(context["draft_json"])
save_draft(draft)
return draft
if __name__ == "__main__":
fake_metrics = lambda s, e: "opens: 41%, clicks: 6%"
fake_model = lambda p: (
'{"subject": "Weekly update", "preview_text": "Results", '
'"body": "Opens were up."}'
if "Return JSON" in p
else "- Opens 41%\n- Clicks 6%\n- Steady week"
)
print(scheduled_newsletter(date(2026, 11, 26), fake_metrics, fake_model, print))Passing fetch_metrics, call_model, and save_draft as arguments means the scheduler only has to call one function. It also means you can test the whole path with no network access, as the __main__ block does.
Idempotency: surviving duplicate runs
An operation is idempotent if running it twice gives the same result as running it once. Schedulers and webhook senders often use "at least once" delivery. That means a retry after a timeout can produce a second run.
For a workflow that creates drafts, a duplicate run could create two drafts, or worse, send two emails. The usual fix is an idempotency key: a string that identifies one logical run. Before doing the work, check whether a run with that key already finished.
- For a schedule, build the key from the workflow name and the period, such as
weekly-newsletter:2026-11-16. - For a trigger, use the event's own ID, such as the post ID or the form submission ID.
import json
import os
def already_done(key, store_dir="runs"):
return os.path.exists(os.path.join(store_dir, key + ".json"))
def record_done(key, result, store_dir="runs"):
os.makedirs(store_dir, exist_ok=True)
with open(os.path.join(store_dir, key + ".json"), "w") as f:
json.dump(result, f)
def run_once(key, job):
if already_done(key):
return None # a previous run already handled this key
result = job()
record_done(key, result)
return resultA file store is enough for a single machine. If several machines can run the job, use a shared store such as a database table with a unique constraint on the key, because two machines can both pass the already_done check at the same moment.
Handling failures
Automatic runs fail for ordinary reasons: the model API times out, a data source is empty, or the model returns text that fails validation. Plan for each.
- Retry transient errors with a delay that grows between attempts, and a small maximum such as three tries. Retrying a validation failure with the same prompt usually produces the same failure, so retry once at most, then stop.
- Check inputs before spending a model call. If the metrics fetch returns nothing, stop and report that. Do not let the model write a report about missing data, because it may invent numbers.
- Fail loudly. Send an alert to a person or channel when a run ends in error. Include the workflow name, the key, and the step that failed.
- Keep a log of each run: the key, start and end time, the template version, the inputs used, and the outputs. This log is what you inspect when someone asks why Tuesday's post said something odd.
Controlling cost and volume
A trigger can fire many times in a short burst. Importing 500 leads can create 500 events, and each might start a model call. Three controls help:
- Rate limits. Cap runs per minute so you stay within the model provider's limits.
- Batching. Collect events for a few minutes and process them together when the task allows it.
- Deduplication. Use the idempotency key so repeated events cost nothing.
Also set a maximum number of runs per day for each workflow. If the cap is hit, stop and alert rather than continuing to spend.
Where review fits
Decide what the run produces at the end. There are three common patterns:
- Draft and notify. The run saves a draft in your CMS or email tool and messages a reviewer. This is the right default.
- Approve then send. The run prepares everything and waits for a person to press approve. Use this for anything customer-facing and hard to retract.
- Auto-publish with checks. Only for low-risk, tightly validated output, such as an internal report. Keep it behind passing validation and a kill switch.
A kill switch is a single setting that turns the workflow off without editing code, such as a flag read at the start of every run. Check it first in your entry function.
Where schedules actually run
The workflow code does not care what starts it. Common options:
| Option | Good for | Watch out for |
|---|---|---|
| `cron` on a server | Simple, single-machine jobs | The machine must stay up; failures are easy to miss |
| Cloud scheduler plus a function | Teams already on a cloud platform | Default time zone, execution time limits |
| CI service on a schedule | Workflows kept in a code repository | Schedules can be delayed under load |
| No-code automation platform | Triggers from forms, CRMs, and spreadsheets | Hard to test and version; keep the logic small |
Whichever you pick, keep the scheduler thin. It should only call your entry function with the date or event. The logic stays in the workflow, where you can test and version it.
Visualizing a triggered run
Common mistakes
- Hard-coded dates in templates, so next week's run repeats this week's period.
- Ignoring time zones, so a post goes out at the wrong hour for the audience.
- No idempotency key, so retries create duplicates.
- Silent failure, with no alert and no log.
- Testing only the happy path. Test an empty data source, an invalid model reply, and a duplicate event before you turn the schedule on.
- Putting secrets in the schedule definition. Store API keys in the platform's secret store or environment variables, not in the workflow file.
Rolling out safely
- Run the entry function by hand with a fixed date and fake dependencies.
- Run it by hand against real data, with the draft going to a test location.
- Turn on the schedule, but keep the output as draft and notify.
- Watch several consecutive runs and compare them with the checklist from the evaluation chapter.
- Only then consider reducing review, and only for low-risk output.
Exercise
A trigger starts a social-post workflow whenever a blog post is published. The publishing system sometimes sends the same event twice within a minute. What key would you use to prevent two sets of posts, and what would you do if two machines process events?
Show answer
Use the blog post's ID (or the event's own ID) as the idempotency key, and check it before doing any work, recording it when the run finishes. If two machines can process events, a file check is not safe, because both may pass the check at once. Use a shared store such as a database table with a unique constraint on the key, so only one insert succeeds and the other run stops.
Exercise
Your weekly report is scheduled with 0 8 * * 1 on a cloud scheduler. Your team is in a UTC+2 time zone and reports arrive at 10:00 in summer but 09:00 in winter. What is the likely cause and the fix?
Show answer
The scheduler runs in UTC, so 08:00 UTC is 10:00 local during UTC+2 and 09:00 after clocks change to UTC+1. Set the scheduler's time zone explicitly to the team's local zone (if it supports one), or accept the shift and adjust the hour. Also compute the report's date range inside the workflow, not from the schedule definition.