Claude Code Automation: Every Way to Run It Unattended

Claude Code can work without you. There are eight or so ways to make it do so, from a single claude -p in a cron job to cloud scheduled tasks that fire on a GitHub event, and they differ on what matters: where the run happens, what it can see, what triggers it, and what becomes of it when your laptop is closed. This page puts them all on one map, with a decision table, a tested recipe for each, and the four problems every unattended run hits. Every behavior marked as tested comes from 17 runs we made on 2026-11-17 with Claude Code 2.1.326, in disposable Docker containers; the rest is quoted from the official docs, with the link. Each topic that deserves more than a section links to its own deep dive.

The short answer: claude -p is the building block. Run it from cron on a machine that stays on when the job needs your local files and services, from GitHub Actions when it reacts to the repository, and as a cloud scheduled task when it needs neither your machine nor more than one run an hour. Whatever the trigger, decide the permissions in advance and check the JSON result, not just the exit code.

Claude Code automation at a glance

Mechanism Trigger Runs on Sees your local files Minimum interval Laptop closed Billing Best for
claude -p (headless) Whatever calls it Wherever you run it Yes – Depends on the host Subscription login or API key The building block of everything below
cron / systemd timer + claude -p Schedule Your machine or server Yes 1 minute Stops on a laptop, fine on a server Same as claude -p Nightly jobs that need local services, databases, other CLIs
/loop Interval, inside an open session Your terminal session Yes 1 minute Stops Subscription Watching a deploy or a PR for an afternoon
Desktop scheduled tasks Schedule Your machine, through Claude Desktop Yes 1 hour in the forms Skipped, one catch-up on wake Subscription Personal daily routines on your own computer
Cloud scheduled tasks (ex routines) Schedule, API call, GitHub event Anthropic's cloud No, fresh clone 1 hour Keeps running Subscription usage (Pro and up) Repository jobs that need no local state
GitHub Actions + claude-code-action PR, issue, comment, @claude, schedule A GitHub runner Repository checkout only 5 minutes (GitHub's limit) Keeps running API key or subscription token, plus Actions minutes PR review, issue to PR, CI fixes
Hooks Events inside a session (tool call, stop) Wherever Claude Code runs Yes – – Nothing extra Guards, logs and notifications around any of the above
Agent SDK Your code Anywhere Yes – Depends on the host API key Building your own agent or product

Sources: scheduled tasks (comparison table), cloud scheduled tasks, Desktop scheduled tasks, GitHub Actions, Agent SDK.

One line per row:

Recent versions also have claude --bg: it starts a session in the background and returns at once, and claude agents, claude logs <id> and claude attach <id> find it again. It keeps a long task running without a terminal, but it is not a trigger: something still has to start it.

The building block: headless mode (claude -p)

-p (or --print) runs one prompt with no interactive interface and exits. The dedicated Claude Code headless mode article goes deeper; here is what an automation needs.

Prompt, output formats and exit codes

claude -p "Reply with exactly the word pong and nothing else." --output-format json

--output-format takes text (the default), json (one result object at the end) or stream-json (one JSON event per line, as it happens). stream-json needs --verbose: without it, our run stopped before starting with Error: When using --print, --output-format=stream-json requires --verbose and exit code 1.

The JSON result is what your script should read. From our run:

{"type":"result","subtype":"success","is_error":false,"num_turns":1,"result":"pong",
 "total_cost_usd":0.0724,"permission_denials":[],"terminal_reason":"completed", "session_id":"..."}

total_cost_usd is a client-side estimate at API prices, also shown on a subscription. session_id lets a later step continue the same conversation with --resume. Add --json-schema '<schema>' and the validated answer lands in structured_output, which saves you from parsing prose: our test asked whether a README existed and got {"status":"ok","summary":"..."} back, ready for jq.

The docs say Claude Code "exits with code 0 on success and a non-zero code when the run fails". What that means in practice, on 2.1.326:

Situation (tested) Exit code What the JSON says
Task done 0 "subtype":"success"
Every tool call refused (nothing allowed) 0 permission_denials lists the refused calls
--max-turns 1 reached 1 "subtype":"error_max_turns", "is_error":true
--max-budget-usd 0.01 reached 1 "subtype":"error_max_budget_usd", spent $0.074
Not logged in 1 "is_error":true, "result":"Not logged in · Please run /login", but "subtype":"success"
--bare with only a subscription login 1 Same "Not logged in"
stream-json without --verbose 1 Nothing, the error is on stderr
Stopped by timeout --preserve-status (SIGTERM) 143 Nothing
Stopped by timeout (default) 124 Nothing
claude not on cron's PATH 127 Nothing, claude: not found on stderr

Two lessons. Read is_error, not subtype: the "not logged in" run says success there. And an exit code of 0 does not mean the work was done, as the next sections show.

Pre-approving tools: --allowedTools, permission modes, --max-turns

Since v2.1.302, a claude -p run with no permission mode set starts in Manual mode and denies any call that would need approval (headless docs). So you decide in advance what the job may do:

claude -p "Use the Write tool to create stamp.txt containing the single word ok. Then run: git status --short" \
  --output-format json --permission-mode dontAsk \
  --allowedTools "Write" "Bash(git status *)"

That run wrote the file and ran git status, nothing else. The tools that matter:

The silent refusal when nothing is allowed

Run the same kind of task without any rule, and nothing happens, successfully:

$ claude -p "Run this exact shell command and nothing else: date -u > stamp.txt" --output-format json; echo "exit=$?"
{"subtype":"success","is_error":false,"result":"I ran `date -u > stamp.txt`, but it didn't go through. Claude Code needs
your approval before a shell command writes a file...","permission_denials":[{"tool_name":"Bash", ...}]}
exit=0

No file, exit code 0. A cron job that only checks the exit code reports success for a run that did nothing. Check the denials:

jq -e '.is_error == false and (.permission_denials | length == 0)' out.json >/dev/null || echo "run failed or was refused"

Our dangerously-skip-permissions guide covers every permission mode, the hard stops that hold even with the flag, and 24 tests of them.

Reusable units: skills, slash commands, CLAUDE.md

A scheduled job with a 40-line prompt in a crontab is unmaintainable. Put the prompt in the repository instead.

Turn a repeated prompt into a skill, call it headless

A skill is a folder with a SKILL.md. Ours, committed in .claude/skills/release-notes/SKILL.md:

---
name: release-notes
description: Summarize the last commits as release notes
---
Run `git log --oneline -5` and write the result as a markdown bullet list under a "## Release notes" heading. Output only the list.

Then the job is one line:

claude -p "/release-notes" --output-format json --allowedTools "Bash(git log *)"

Our run returned the heading and the three commits of the test repository, in 2 turns. The docs confirm that "user-invoked skills and custom commands work" in -p: Claude Code expands /skill-name before running. Terminal-only commands such as /login don't. The prompt is now versioned, reviewed in pull requests, and the same for a person typing /release-notes and for cron. CLAUDE.md plays the same role for conventions every run should follow (test command, branch naming, what never to touch).

One caveat: --bare, which the docs recommend for scripted calls and which "will become the default for -p in a future release", skips the auto-discovery of hooks, plugins, MCP servers and CLAUDE.md, and only accepts an API key. Skills still resolve via /skill-name; pass the rest explicitly (--append-system-prompt-file, --settings, --mcp-config).

Hooks: run a check or a notification on every tool call or stop

Hooks are shell commands Claude Code runs on lifecycle events, and they fire in -p too. Our test passed this settings file with --settings:

{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"echo stop-hook-fired $(date -u +%H:%M:%S) >> /out/hook.log"}]}]}}

and the log got its line, stop-hook-fired 09:07:12, when the run ended. Three hooks matter for automation:

A future best Claude Code hooks article will collect the useful ones.

Running it on a schedule

Four schedulers, four very different contracts. The planned Claude Code scheduled tasks article covers the built-in ones in depth.

cron or systemd timers on your own machine

The most flexible option, and the one where you build the safety yourself. Our wrapper, with every piece tested in a container:

#!/bin/bash
# /usr/local/bin/claude-nightly.sh, called by cron
set -uo pipefail
export PATH="$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin"   # cron's PATH doesn't have claude
cd /srv/repos/myapp || exit 1

exec 9>/tmp/claude-nightly.lock                                 # one run at a time
flock -n 9 || { echo "$(date -u +%FT%TZ) previous run still going, skipping" >&2; exit 75; }

claude auth status >/dev/null || { echo "claude is not logged in" >&2; exit 1; }

LOG="$HOME/logs/claude-nightly-$(date -u +%F).json"
timeout --preserve-status 30m claude -p "/nightly-triage" \
  --output-format json --permission-mode dontAsk \
  --allowedTools "Read" "Grep" "Glob" "Bash(gh issue list *)" "Bash(gh issue view *)" "Bash(gh issue edit *)" \
  --max-turns 40 --max-budget-usd 3 --no-session-persistence < /dev/null > "$LOG"
code=$?

ok=$(jq -r 'if .is_error == false and (.permission_denials | length == 0) then "yes" else "no" end' "$LOG" 2>/dev/null || echo no)
if [ "$code" -ne 0 ] || [ "$ok" != yes ]; then
  curl -fsS -X POST -d "claude-nightly failed: exit=$code, see $LOG" "$ALERT_WEBHOOK_URL"
fi
exit "$code"
0 2 * * * . $HOME/.claude-cron.env; /usr/local/bin/claude-nightly.sh >> $HOME/logs/cron.log 2>&1

Why each line is there:

A systemd timer does the same with Persistent=true to run a missed job at boot, and journalctl for the logs.

/loop: repeat a prompt inside an open session

/loop 5m check whether the deploy finished and tell me if it failed

/loop turns a prompt into a session-scoped cron task (the CronCreate tool). The limits, from the docs: 1 minute minimum, up to 50 tasks per session, recurring tasks expire after 7 days, times are in local time, and runs are shifted by a jitter (an hourly task can run up to 30 minutes late). "Closing the terminal or letting the session exit stops them firing", and there is no catch-up: a fire missed while Claude was busy runs once when it becomes idle. CLAUDE_CODE_DISABLE_CRON=1 turns the scheduler off.

We tried the obvious shortcut, /loop inside claude -p. Claude created the task (CronCreate with * * * * *), answered once, and the process exited after 12 seconds with code 0. No tick ever fired. The docs only mention self-paced loops keeping a -p run open. Use /loop to watch something for an afternoon in a session you keep open; for anything that must happen tomorrow, pick another row.

Desktop scheduled tasks: local, while the app is open

The Claude Desktop app (1.1.5368 or later) can schedule a task on a local folder: hourly, daily, weekdays, weekly or a custom cron, at most once an hour from the forms. It "only fires while the app is open and your computer is awake"; "closing the laptop lid still puts it to sleep". If the computer sleeps through a run, that run is skipped, and on wake Desktop starts exactly one catch-up run for the most recent missed time within the last seven days (docs).

Runs use your Claude Code permission settings unless you set a mode on the task; a run that needs a permission waits for you in its session. Turn on Worktree in the task's form so each run gets its own git worktree: by default it works in your folder, "including uncommitted changes".

Cloud scheduled tasks (formerly routines)

Anthropic renamed routines to scheduled tasks; the CLI command is /schedule (alias /routines), the web page is claude.ai/code/routines. They run on Anthropic's cloud, so they are the built-in way to keep going with your laptop closed. What the docs say, as of today:

The API trigger turns any system into an event source:

curl -X POST "https://api.anthropic.com/v1/claude_code/routines/$TRIGGER_ID/fire" \
  -H "Authorization: Bearer $ROUTINE_TOKEN" \
  -H "anthropic-beta: experimental-cc-routine-2026-04-01" \
  -H "anthropic-version: 2023-06-01" -H "Content-Type: application/json" \
  -d '{"text": "Sentry issue 4812: TypeError in checkout.ts line 88"}'

The text reaches the run wrapped as untrusted input, and the saved prompt has to refer to it. The token is per task, shown once.

Which scheduler for which job

The job needs Pick
Your local services, a database, another CLI, a GPU cron or systemd on a machine that stays on
To run with your laptop closed, on the repository alone Cloud scheduled task, or a GitHub Actions schedule:
More than one run an hour cron, or GitHub Actions (5 minutes minimum)
To watch something for the next few hours /loop in a session you keep open
A personal routine on your own computer, with a UI Desktop scheduled task
A result you can open as a session and continue Cloud or Desktop scheduled task

Cloud vs your own machine is the same trade-off as with other agents; our Cursor background agents post compares both sides.

Reacting to events: GitHub Actions and webhooks

anthropics/claude-code-action on PRs, issues and comments

The fastest setup is /install-github-app in Claude Code: it installs the Claude GitHub App, stores a secret and opens a pull request with the workflow files (you need admin rights on the repository and an authenticated gh). The action has two modes (docs):

name: Claude
on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]
jobs:
  claude:
    if: contains(github.event.comment.body, '@claude')
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
      issues: write
      id-token: write
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 1
      - uses: anthropics/claude-code-action@v1
        with:
          claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}   # or anthropic_api_key

Things that bite: the action runs Claude in auto mode by default (pass --permission-mode in claude_args to change it); only users with write access can trigger it on issue and PR events; secrets are not given to pull requests from forks on public repositories; and commits made with the default GITHUB_TOKEN don't trigger your other workflows, so CI won't run on Claude's commits if you pass it. Flags such as --max-turns and --model go in claude_args. The planned Claude Code GitHub Actions article goes deeper.

Scheduled workflows in Actions

on:
  schedule:
    - cron: "0 7 * * 1"   # Mondays 07:00 UTC

GitHub's cron is in UTC, runs only from the default branch, can start late under load, and the shortest interval is 5 minutes. In public repositories, GitHub turns schedules off after 60 days without activity. With a plain-text prompt, Claude has no shell or GitHub API access until you grant tools with --allowedTools in claude_args. Each run also costs Actions minutes.

Webhooks and the API trigger of cloud tasks

For events that don't come from GitHub (a Sentry alert, a form, a failed deploy), you have two built-in paths: the API trigger of a cloud scheduled task shown above, or a GitHub workflow started by repository_dispatch that runs the action. Outside these, any small endpoint that receives the webhook and runs claude -p on your machine does the job, with the same wrapper as the cron one.

Chaining steps: from one prompt to a workflow

Shell pipelines and the Agent SDK

A session id is all you need to chain claude -p calls:

sid=$(claude -p "Read ISSUE.md and plan the fix. Do not edit anything yet." \
  --output-format json --permission-mode dontAsk --allowedTools "Read" "Grep" "Glob" | jq -r .session_id)
claude -p "Implement the plan. Run the tests. Commit on a new branch." --resume "$sid" \
  --output-format json --permission-mode acceptEdits \
  --allowedTools "Bash(npm test *)" "Bash(git switch *)" "Bash(git add *)" "Bash(git commit *)" \
  --disallowedTools "Bash(git push *)"

When the glue grows past a page of bash, the Agent SDK gives you the same agent loop in TypeScript (@anthropic-ai/claude-agent-sdk) or Python (claude-agent-sdk):

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Review utils.py for bugs that would cause crashes. Fix any issues you find.",
  options: { allowedTools: ["Read", "Edit", "Glob"], permissionMode: "acceptEdits" },
})) {
  if (message.type === "result") console.log(message.result);
}

Authentication is an API key. The SDK docs are explicit: "Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK."

Handing work between Claude Code and another CLI

The most useful chain we run is two different models: one writes, the other reviews. Codex has its own headless mode, codex exec:

git diff main...HEAD > /tmp/change.diff
codex exec --sandbox read-only "Review this diff for bugs and missing tests. List each finding with file and line: $(cat /tmp/change.diff)"

Then feed the remarks back to Claude with --resume "$sid". A reviewer that didn't write the code finds different things; our Codex vs Claude Code benchmark measured how differently the two work on the same tasks. The headless flags of Copilot CLI and Gemini CLI are in our Copilot and Gemini comparisons.

What breaks when nobody is watching

Permissions: allowlist, or skip everything inside a box

Two sane setups, nothing in between:

Remember that -p skips the workspace trust dialog: per the docs, a -p run without --bare runs the project's hooks and connects its .mcp.json servers "even in a folder you've never trusted". Don't point a scheduled job at a repository you haven't read. The full picture is in the dangerously-skip-permissions guide.

Knowing it failed: exit codes, logs, notifications

Three checks, in this order: the exit code (non-zero means crashed, capped, killed or not logged in), is_error in the JSON, then permission_denials. Keep the JSON of every run, dated, for a few weeks: it has the result, the cost and the session id to --resume and ask "what happened?". Send an alert on any of the three, and use a Stop or StopFailure hook for notifications that must leave even when your wrapper is not involved. The silent failure to fear most is the one that didn't run at all: a cron line with a typo, a cloud task turned off after its GitHub connection broke for 72 hours. A daily "I ran" message is cheaper than discovering a week of silence.

Usage limits in the middle of a run

Scheduled runs draw from the same five-hour and weekly windows as your interactive use (cloud tasks included). Anthropic's support page says that when the five-hour limit hits mid-response, Claude Code may finish the current step and show "Usage limit reached · wrapping up", then stops until the window resets, unless usage credits are on. What a claude -p run does then is not documented, and we did not reach a limit for this article. Plan for it anyway: a StopFailure hook on rate_limit|billing_error, nightly jobs scheduled away from your working hours so they don't eat the window you need in the morning, and --fallback-model for the case where a model is busy rather than your plan exhausted.

Subscription or API key for unattended runs

What the docs say today:

Two traps. ANTHROPIC_API_KEY takes precedence over CLAUDE_CODE_OAUTH_TOKEN, so a key left in the environment silently moves your jobs to API billing. And --bare never reads OAuth: our --bare run with a valid subscription login answered "Not logged in" and exited with 1.

Review before anything ships

An unattended agent that pushes to main is a deploy pipeline with no reviewer. Let it commit on a branch, deny git push (or allow only pushes to its own prefix, as cloud tasks do with claude/), and have a person read the diff before it merges. For pull requests, require a review in the branch protection rules, so even an agent with write access can't merge its own work.

Claude Code automation examples you can copy

Each recipe gives the trigger, the command, the permissions and where the result lands. The linked templates are the same jobs as ready-made SideHub workflows.

How we automate Claude Code on our own machines (SideHub)

The built-in options leave a gap we kept falling into. Cloud scheduled tasks run on a fresh clone, without our local services, databases or other CLIs. Desktop tasks and /loop stop when the app or the session closes. cron and CI run anywhere, but give no view of the run and no review step. SideHub is what we built for that: an agent you install on your own machine runs the same CLIs, in a terminal on that machine, launched from the web.

What it does not do: it needs the agent running on a machine that stays on. A scheduled run that fires while the machine is offline is skipped; when the agent comes back, the last missed one is caught up once, not every one, and you get one alert per outage. Webhook and event triggers are not retried. There is no automatic switch to another CLI when a plan runs out, yet. Schedules, webhooks and event triggers need the Pro plan.

This article went through that pipeline: a weekly workflow chose the keyword and wrote the brief, a Claude Code step ran the tests and drafted the page, a person approved it, and a last step opened the pull request that published it.

Troubleshooting

How we tested

Each case ran in its own docker run --rm container from debian:bookworm-slim with git, jq and flock, as a non-root user (uid 1001), on a fresh git repository. Only a copy of the Claude Code 2.1.326 binary and a read-only copy of its sign-in file were mounted: no home directory, no other credentials.

docker run --rm --user 1001:1001 -e HOME=/home/dev \
  -v "$PWD/scripts:/bench/scripts:ro" -v "$PWD/results:/out" \
  -v "$PWD/creds/claude:/opt/claude:ro" \
  -v "$PWD/creds/credentials.json:/creds/credentials.json:ro" \
  ccabench:1 /bench/scripts/in-container.sh refusal

The script copies the binary to ~/.local/bin, as the native installer does, then runs one claude -p per case with --strict-mcp-config --no-session-persistence < /dev/null, and records the exit code, stdout, stderr and the files left on disk. 17 cases: JSON output, the silent refusal (with and without --permission-prompts none), an exact allowlist, --max-turns, --max-budget-usd, a skill called headless, a Stop hook, --bare, no login, cron's PATH, stream-json without --verbose, --json-schema, timeout with and without --preserve-status, a flock wrapper, and /loop inside -p. Default model (Claude Opus 5.5) on a Claude Max plan, $0.90 in total at API prices according to total_cost_usd for the 10 runs that reported it. One run per case: these tests check what the CLI does, not how often a model gets a task right. Facts about cloud and Desktop scheduled tasks and GitHub Actions are quoted from Anthropic's docs as of 2026-11-17; cloud scheduled tasks are a research preview and their limits may change.

The verdict

Claude Code automation is not one feature but one command, claude -p, and a choice of who calls it. Pick by where the job must run: cron or systemd on a machine that stays on when it needs your local world, GitHub Actions when it starts from the repository, a cloud scheduled task when it needs neither and once an hour is enough, /loop and Desktop tasks for what can stop when you close the lid. Then do the four things every unattended run needs: permissions decided in advance with an exact allowlist, a check of is_error and permission_denials rather than the exit code alone, a notification when it fails or hits the plan limit, and a person who reads the diff before anything is pushed. The template gallery has the examples above as ready-made workflows, if you'd rather start from one.