Skip to content

Claude · Loops and autonomous runs: /loop, iteration, and scheduling

Run autonomous loops with iteration and scheduling.

  • Lesson 5 of 5
  • About 9 min read
  • Quiz of 5 questions
  • +210 XP

Some work is the same task on repeat until a condition is met:

  • "Keep fixing bugs until every test passes."
  • "Check the deploy every few minutes until it's live, then tell me."
  • "Every morning at 8, summarize what changed in the repo overnight."

None of these is a single action. Each one is a loop with a stop condition. Claude Code handles them in a few ways, depending on whether the repetition happens inside one run, on a timer inside your session, or across many scheduled runs.

This lesson covers three things: iterating until a goal is met, using /loop to re-run a prompt on an interval, and scheduling an agent to fire on a cadence. It also covers the guardrails that keep an unattended run from burning your token budget or your codebase.

When a loop is the right tool

A loop is worth reaching for when three things are true:

  • The task repeats. You are doing the same operation more than once (poll, retry, iterate).
  • There's a measurable stop condition. Tests pass, a build is green, a file exists, or a value crosses a threshold. If you cannot describe "done" precisely, you cannot loop safely.
  • Each pass improves the outcome, or you're waiting on an external change. Fixing tests improves things with each pass. Polling a build waits for something outside your control.

If these don't hold, a single call is cleaner and cheaper. "Refactor this function" is one call. "Refactor every function until the linter is silent" is a loop.

Three ways to iterate in Claude Code

Claude Code runs in your terminal with access to your files, your shell, and your git history. You can get repetition in three ways.

Inside a single run. You put the task, the stop condition, and a hard cap in your prompt. Claude does the work, checks its own output against the condition, and repeats until the condition is met or the cap is hit. This is the "keep going until X" pattern.

With `/loop`. This command re-runs a prompt (or another slash command) on a fixed interval while your session stays open. For example, /loop 5m check whether the deploy is live and tell me when it is. It suits light polling and babysitting tasks you want to run alongside your normal work. These loops are tied to the session. Close Claude Code and they stop, and recurring loops also expire automatically after a set period, so they won't run forever. Check the Claude Code documentation for the current interval syntax and limits.

With a shell loop around headless mode. You call claude -p "..." (one prompt that runs and exits) from a bash loop or script. Your script owns the repetition, the delay, and the exit logic. This works when you need exact control or no interactive session at all.

Here's the in-session pattern:

bash
claude
> Run the full test suite with pytest. If any tests fail,
  read the failure output, fix the SOURCE code (not the tests),
  and run the suite again. Repeat until all tests pass or you
  have made 10 attempts. If you hit 10 attempts, stop and tell me
  what is still failing.

The prompt has three parts. The task is explicit (run pytest, fix code). The stop condition is unambiguous (all tests pass). The hard cap (10 attempts) keeps a stubborn bug from spinning forever.

Here's the same polling job done two ways. With /loop, inside a session:

/loop 2m curl https://myapp.example.com/health. If it returns 200,
post a one-line 'shipped' note and stop looping.

With a shell script, where you control everything:

bash
# Poll a deploy every 30s, up to 20 times, until it returns 200
for i in $(seq 1 20); do
  if curl -sf -o /dev/null https://myapp.example.com/health; then
    claude -p "The deploy is live. Post a one-line 'shipped' note."
    break
  fi
  sleep 30
done

/loop is quicker to set up. The script is stricter, because the cap and the delay live in code and Claude only runs when there's something to do.

Why the stop condition must be machine-checkable

"Fix the code until it looks good" is not a loop condition. Claude has no objective signal to check, so it will either stop at an arbitrary point or keep polishing forever. "Fix the code until pytest exits 0" is checkable, because an exit code is a fact.

Good loop conditions are things a command can answer:

  • pytest exit code is 0
  • npm run build succeeds
  • git status shows no uncommitted changes
  • a specific string appears in a log file
  • an HTTP endpoint returns 200

If you can express "done" as a command that returns success or failure, you have a loop you can trust to stop on its own.

Check your reading

According to the lesson, what is the essential difference between a task that warrants a loop and one that should be a single call?

Worked example: keep fixing until the suite is green

You have a test suite with a handful of failures after a messy merge. You want Claude to run the tests, read what broke, patch the source, and run again until the whole suite is green.

bash
claude
> Goal: make the entire test suite pass.
  1. Run: pytest -x --tb=short
  2. If exit code is 0, the goal is met. Stop and summarize what changed.
  3. If tests failed, read the traceback, fix the SOURCE code only.
     Never edit or delete tests to make them pass.
  4. Commit each fix with a clear message, then repeat from step 1.
  Budget: stop after 8 attempts and report if not green by then.

Step 3 blocks the most common shortcut an autonomous agent will take, which is deleting the failing test. Asked to "make tests pass" with no constraint, a model may decide removing the test is the fastest route. "Fix the SOURCE code only" rules that out.

The commit-per-fix instruction gives you a clean git history and an easy revert if one fix was wrong. When the run ends, you review the diff, not the process.

A single fix-and-stop would clear one round of failures and likely reveal a second round it never touched. Iterating works through all of it while you do something else.

Video

Autonomous Test-Fixing Loops in Claude Code

walks through the green-tests iteration end to end, including the git-per-fix pattern and reviewing the final diff

Watch on YouTube

Guardrails for unattended runs

Once a run proceeds without you watching each step, it can do damage or waste money at machine speed. Three guardrails are non-negotiable.

1. A hard budget

Every loop needs a ceiling that does not depend on the model's judgment. An attempt count in the prompt is the simplest. In a script, cap the iterations in code (for i in $(seq 1 20)). With /loop, pick an interval that matches how fast the thing you're watching changes. Every tick is a model call, so a 1-minute loop left running all afternoon adds up. Cancel the loop once it has done its job. The budget is a backstop for when the stop condition never triggers.

2. A clear stop condition

This is the primary safety mechanism, and the budget is only the backstop. A run with a budget but no real stop condition burns to the cap every time. For /loop, write the stop instruction into the prompt itself ("when it returns 200, report and stop").

3. A human review gate

For anything that changes state (writes code, pushes commits, sends messages, calls a paid API), decide in advance where a human signs off. There are two common patterns:

  • Review at the end. The run is fully autonomous but only produces a branch and a diff. You review before merging.
  • Review per action. Claude Code's permission prompts require your approval for risky operations such as shell commands, writes outside a directory, or network calls. This is slower, but appropriate when the blast radius is large.

Use Claude Code's permission settings to constrain which tools the agent may use and which directories it may touch before it runs unattended. The Claude Code documentation covers permission modes in detail.

A useful rule: the more autonomous the run, the tighter the sandbox. A run you watch can have broad permissions. One that fires at 3am should be able to touch almost nothing except the one thing it's there to do.

Check your reading

Why does the lesson insist that you must be able to describe 'done' precisely before using a loop?

Scheduling: runs that fire on a cadence

Iteration answers "repeat until done." Scheduling answers "run again later, on a rhythm." Examples include a daily digest, a nightly dependency check, or a weekly report.

/loop handles short-lived recurrence while your session is open. It won't survive a closed laptop. For durable schedules, use your operating system's scheduler (cron on Linux and macOS, Task Scheduler on Windows) or a CI runner like GitHub Actions.

Here's a weekday repo digest as a cron entry using headless mode:

bash
# Every weekday at 8:00 AM, summarize overnight git activity
0 8 * * 1-5 cd /home/me/project && \
  claude -p "Summarize commits from the last 24 hours grouped by \
  author. Flag anything touching auth/ or billing/. Output markdown." \
  >> ~/digests/daily-$(date +\%F).md 2>&1

The -p flag runs one prompt and exits, which is what a scheduled job needs. There's no interactive session, the start and finish are clean, and the output goes to a file. Add an MCP server and the same run could post the digest to Slack or open a GitHub issue. See the Model Context Protocol docs for how to set up those connections.

For schedules that live with your repo rather than one machine, use Anthropic's Claude Code GitHub Action. It runs Claude on a schedule or on repo events, such as a new PR or an issue with a certain label. A weekly on: schedule workflow that audits dependencies and opens a PR is a clean, reviewable autonomous run.

Scheduled runs need the same guardrails, more so

Nobody is watching when a scheduled job fires. Give it a budget and a stop condition, even for a one-shot digest, so a hung external call doesn't leave it running. Route anything that changes state through a review gate. A scheduled run that opens a PR is safe. One that pushes to main is a foot-gun waiting for a bad night.

Choosing the right shape

  • Single call: one task, no repetition, you're present. "Refactor this module."
  • In-session iteration: task, checkable stop condition, and attempt cap in one prompt. "Fix until tests pass, max 8 attempts."
  • /loop: re-run a prompt on an interval while your session is open. "Every 5 minutes, check CI on my PR and tell me when it's green."
  • Shell loop around claude -p: your script owns repetition, delay, and cap. Use it when you need exact control.
  • Scheduled run: cron or GitHub Actions running claude -p, usually a fresh task each time. "Every morning, digest the repo."

These shapes combine well. A nightly GitHub Actions workflow can have Claude iterate inside the run until its dependency upgrades pass CI. The schedule sets the cadence, and the iteration happens inside each run.

Key Takeaways

  • Loop only when the task repeats and "done" is machine-checkable. If the stop condition can't be a command that returns success or failure, you don't have a safe loop yet.
  • /loop re-runs a prompt on an interval inside your session. It's good for polling and babysitting, but it stops when the session ends and loops expire on their own.
  • For iteration toward a goal, put the task, stop condition, and attempt cap in one prompt. For strict control, wrap claude -p in a script that owns the loop.
  • Every unattended run needs a hard budget, a clear stop condition, and a human review gate on anything that changes state.
  • Close off the obvious shortcut. "Make tests pass" invites deleting tests, so say "fix source only, never edit tests" and commit each fix.
  • For durable schedules, use cron, Task Scheduler, or GitHub Actions running claude -p. The more autonomous the run, the tighter the sandbox.

Quiz

Did the essentials stick?

3 questions, one at a time. Each one right on the first try brings the probe closer to the planet.

Question 1 of 3

A developer wants Claude to poll a CI deploy every minute and notify them once it goes live. Which /loop flavor fits, and why?