Build Idempotent Cron Jobs with Atomic State
A reliable recurring job can run twice without creating two outcomes. That property—idempotency—matters because processes can retry, machines can restart, and an operator may rerun a job while investigating a failure.
Separate observation, decision, action, and commit
Use four explicit phases:
- Observe: read the external source and current local checkpoint.
- Decide: determine whether there is genuinely new work.
- Act: perform the bounded side effect once.
- Commit: save the new checkpoint only after the action succeeds and is verified.
If the checkpoint is written before the external action succeeds, the next run can skip unfinished work. If it is never written, every run may repeat the same action.
Choose an idempotency key
Derive a stable key from the event or intended outcome: a source record ID, content hash, message ID, or timestamp-plus-object identifier. Store the key with enough result metadata to verify what happened, but never store secrets in logs or public state.
For file-backed state, write a complete temporary file and atomically replace the prior file only after validation. Do not stream partial JSON directly over the live checkpoint.
Decide whether an agent is needed
If a script already produces the exact final alert, a script-only cron job avoids an unnecessary model turn. Use an agent when interpretation, summarization, or judgment is the actual task.
Silence should be a first-class result. A monitoring job that finds no material change should produce no delivery rather than a daily “nothing happened” message.
Reliability checklist
- The job has a stable idempotency key.
- Observation does not mutate external state.
- Side effects happen after a clear decision.
- State commits only after verified success.
- State writes are atomic.
- Empty/no-change output stays silent.
- Logs omit credentials and private payloads.
- A rerun produces the same final state.
Common pitfalls
Updating state before delivery
A failed send followed by an advanced checkpoint creates a silent gap.
Using time alone as identity
Clock time is often not a stable event identifier. Prefer a source-provided ID or content hash.
Letting the model own raw state mutation
Keep state transitions deterministic when possible. Let the model interpret content, but let tested code validate and commit the checkpoint.
Verification steps
- Run the job against a fixed test event.
- Confirm one output and one committed idempotency key.
- Run it again without changing the source.
- Confirm no duplicate side effect occurs.
- Simulate a failed action and verify the checkpoint does not advance.
- Simulate interruption during a state write and confirm the prior valid state remains readable.
Official reference
Start with the official Automate Anything with Cron guide, then apply these release-oriented state and retry gates.
