What Is the Claude Code /loop Command? How to Run Recurring AI Tasks in Your Session
The /loop command in Claude Code creates cron jobs that fire prompts automatically on a schedule. Learn how it works, its limits, and when to use it.
When You’re Tired of Typing the Same Prompt Every Day
Most Claude Code users discover the same problem after a few weeks: they’re running the same prompt manually, on repeat, every time they need a status check, a code review, or a fresh summary of recent changes. It works, but it’s busywork. You open a terminal, type something you’ve typed a hundred times, wait for the output, and move on.
The Claude Code /loop command exists to fix that. It lets you schedule prompts to fire automatically on a set cadence — no manual triggering, no cron scripts from scratch, no third-party scheduler. You define what you want Claude to do, you define when you want it to happen, and it runs.
This article covers exactly how the /loop command works, how to set it up in your session, the types of tasks it handles well, where it falls short, and what to do when you need something more than terminal-level scheduling. If you’re exploring how to automate recurring AI tasks — whether with Claude Code or beyond — this is the full picture.
What Claude Code Is and Why Automation Matters
Before getting into /loop specifically, it helps to understand what Claude Code actually is and why its automation features matter more than they might seem at first glance.
Claude Code at a Glance
Claude Code is Anthropic’s terminal-based AI coding tool. Unlike chat interfaces, it runs directly in your development environment. It can read your codebase, make edits, run shell commands, check test output, browse the web, and operate as an autonomous agent — all from the command line.
It ships with a set of slash commands for managing sessions, configuration, memory, and workflow. Commands like /clear, /compact, /config, /memory, and /review let you control Claude’s behavior without leaving the terminal.
The tool also supports non-interactive mode. With the -p flag, you can pass Claude a prompt and pipe the output elsewhere — to a log file, another script, a CI pipeline, or whatever downstream system needs it.
Why Recurring Tasks Are a Real Problem
The issue is that most useful AI automation isn’t one-and-done. Checking whether test coverage dropped. Summarizing recent commits every morning. Monitoring for deprecated API patterns. Reviewing open pull requests. These tasks repeat, and they’re worth automating because the manual effort adds up quickly.
The naive solution is wrapping claude -p "your prompt" in a shell script and adding that script to your system crontab. That works, but it’s fragile. You have to manage authentication state, output logging, error handling, and context manually. The /loop command offers a more managed path from inside Claude Code’s own interface.
The Session Model
One thing to understand upfront: Claude Code operates within sessions. A session has context — files you’ve mentioned, tools you’ve used, memory you’ve loaded. When you close it, that context doesn’t automatically persist for the next run unless you’ve set up memory explicitly.
This matters for /loop because recurring tasks that rely on session continuity have to be set up with that constraint in mind. We’ll come back to this in the limitations section.
What the /loop Command Actually Does
The /loop command in Claude Code is a session-level scheduler. You give it a prompt and a cadence, and it queues that prompt to repeat at the interval you specify — without you having to reinitiate it manually each time.
The Core Behavior
When you run /loop, you’re telling Claude Code to register a recurring task tied to your current session. The command takes two main inputs:
- The prompt — what you want Claude to do on each cycle
- The schedule — how often you want it to run (expressed as a time interval or a cron-style expression, depending on the version)
On each tick, Claude Code fires the prompt as if you had typed it yourself. It executes against the current project context, uses whatever tools you’ve given it permission to use, and produces output it can act on or log.
What “Creates Cron Jobs” Actually Means
The meta description for this article uses the phrase “creates cron jobs,” and that framing is accurate in spirit. Under the hood, /loop sets up a timed execution pattern — similar to how a Unix cron job tells the system to run a command on a schedule.
The difference is that /loop manages this inside the Claude Code process rather than at the operating system level. You don’t need to open your crontab file, specify the full path to a binary, or deal with environment variable issues that commonly plague system-level cron setups for development tools.
The practical implication: if your session is running (and kept alive), the loop runs. If you close the terminal, the session ends and the loop stops. It’s process-bound, not system-bound.
Basic Syntax
The general form looks like this:
/loop "check for new TODO comments and report any added in the last commit" --interval 15m
Or with a more specific schedule:
/loop "run the test suite and summarize failures" --cron "0 9 * * 1-5"
The --interval flag takes values like 5m, 1h, 30s. The --cron flag accepts standard five-field cron expressions for more precise scheduling (specific times, weekdays, etc.).
Some versions of the command also accept a --times argument to cap how many cycles run before the loop terminates — useful when you want a fixed number of automated iterations rather than continuous repetition.
Output Handling
By default, /loop outputs to your terminal session. For unattended operation, you can redirect this using Claude Code’s built-in logging options or by combining the command with shell redirection operators. For persistent logs, pointing output to a file is the most straightforward approach.
How to Set Up Your First /loop Task
Here’s a practical walkthrough for getting a basic recurring task running in Claude Code.
Prerequisites
Before you run /loop, make sure:
- Claude Code is installed and authenticated — you’ve run
claudeat least once and connected your Anthropic account - You’re in the right working directory — Claude Code scopes its context to the current project, so navigate to the right folder first
- Permissions are configured — if your task requires file writes, shell execution, or external requests, verify that the relevant tools are enabled in
/permissionsor your settings file - Your session will stay active — for loops that need to run over hours or days, you need a persistent terminal session (tmux, screen, or a background process)
Step 1: Start a Claude Code Session
Open your terminal and navigate to your project directory:
cd /path/to/your/project
claude
This starts an interactive Claude Code session. You should see the Claude prompt.
Step 2: Define Your Task
Think carefully about what you’re automating. Good /loop candidates are tasks that:
- Produce consistent, interpretable output each time
- Don’t require human decision-making mid-execution
- Are idempotent (running them twice doesn’t cause problems)
- Have a clear, bounded scope
A weak prompt like “review the codebase” will produce inconsistent, hard-to-act-on output. A stronger prompt is specific: “check if any file in the src/ directory imports from deprecated-utils.js and list them.”
Step 3: Run the /loop Command
With a good prompt in hand, run:
/loop "check the src/ directory for any imports of deprecated-utils.js and print the file paths" --interval 1h
You should see confirmation that the loop is registered. Claude Code will display the schedule and the next expected run time.
Step 4: Verify It’s Running
After waiting for one cycle (or testing with a shorter --interval like 1m), confirm the output appears as expected. Check:
- Is the output formatted usefully?
- Is Claude interpreting the prompt correctly?
- Are any tool permissions missing?
If something’s wrong, you can cancel the loop with /loop --cancel and refine the prompt before re-registering.
Step 5: Keep the Session Alive
For any loop that runs longer than your terminal session, use a session persistence tool:
# Using tmux
tmux new -s claude-loop
claude
# then run your /loop command
# detach with Ctrl+B, D
Or use screen:
screen -S claude-session
claude
# run /loop command
# detach with Ctrl+A, D
This keeps the Claude Code session running even if you close your SSH connection or local terminal window.
Step 6: Monitor and Adjust
Check back periodically to review output. If Claude’s responses are drifting or accumulating context that’s no longer useful, you may need to restart the session and re-register the loop — which brings us to one of the key limitations.
Practical Applications for /loop
The /loop command is most useful for tasks that genuinely benefit from periodic, automated attention. Here are specific categories where it tends to add real value.
Continuous Code Quality Monitoring
You can run Claude on a schedule to check for code quality issues that static linters miss — like inconsistent error handling patterns, functions that have grown too long since the last review, or business logic that hasn’t been tested.
/loop "review files changed in the last git commit and flag any functions over 50 lines or missing error handling" --interval 30m
This isn’t a replacement for linting. It’s the kind of review a senior developer would do as a quick sanity check — applied automatically on a cadence.
Automated Test Failure Analysis
When tests break, diagnosing the cause takes time. A loop that runs after each CI cycle can pre-analyze failures:
/loop "run npm test and if any tests fail, identify the most likely cause based on recent code changes" --interval 2h
This pairs well with a logging setup so the output is captured and queryable later.
Commit Summary Digests
For distributed teams or async work environments, a morning briefing from the codebase is useful. A loop that fires early in the workday can pull recent git history and produce a plain-language summary:
/loop "summarize all commits from the last 24 hours in plain language, grouped by feature area" --cron "0 8 * * 1-5"
Dependency and Security Monitoring
Outdated or vulnerable dependencies are a consistent maintenance overhead. You can automate the check:
/loop "run npm audit and list any high or critical vulnerabilities, with recommended actions" --interval 24h
This doesn’t replace dedicated security scanning tools, but it surfaces issues in plain language that’s easier to act on.
Documentation Drift Detection
Documentation that doesn’t match the code it describes is a common problem. A recurring check can catch this:
/loop "compare the API documentation in /docs with the current function signatures in /src/api and report any mismatches" --interval 1d
File-Based Workflow Monitoring
For projects that process files asynchronously — uploads, data pipelines, generated outputs — a loop can confirm expected files are appearing on schedule:
/loop "check the /output directory for files created in the last hour and report if any are missing from the expected list" --interval 1h
This gives you lightweight monitoring without standing up a full observability stack.
Combining /loop with System-Level Cron
For more robust, production-grade scheduling, you’ll eventually want to step outside the Claude Code session and use your operating system’s scheduling infrastructure. System cron is more reliable for long-running schedules because it isn’t process-bound.
When to Use System Cron Instead
Use system cron (or a similar scheduler like launchd on macOS or Task Scheduler on Windows) when:
- Your task needs to survive system reboots
- You need guaranteed execution even when Claude Code isn’t actively running
- You want centralized logging via the system’s standard output capture
- You’re running tasks on a remote server where session persistence is complex
Writing a Claude Code Shell Script
The starting point is a simple shell script that invokes Claude Code non-interactively:
#!/bin/bash
# claude-daily-check.sh
cd /path/to/your/project
claude -p "summarize all commits from the last 24 hours by feature area" >> /var/log/claude-daily.log 2>&1
Make it executable:
chmod +x claude-daily-check.sh
Adding to Your Crontab
Open your crontab:
crontab -e
Add the entry:
0 8 * * 1-5 /path/to/claude-daily-check.sh
This runs the script at 8 AM on every weekday.
Handling Authentication in Cron Environments
A common issue: Claude Code needs authentication, but cron jobs run in minimal shell environments that may not inherit your user session’s auth state.
To handle this:
- Make sure your Claude Code credentials are stored in a persistent location (usually
~/.config/claude/or similar) - Set the
HOMEenvironment variable explicitly in your cron entry:
0 8 * * 1-5 HOME=/home/yourusername /path/to/claude-daily-check.sh
- Test your script by running it manually as the cron user to verify it authenticates correctly before relying on it unattended
Logging and Error Handling
For any production loop, capture both stdout and stderr:
claude -p "your prompt" >> /var/log/claude-task.log 2>&1
Add timestamps to make log review easier:
echo "=== $(date '+%Y-%m-%d %H:%M:%S') ===" >> /var/log/claude-task.log
claude -p "your prompt" >> /var/log/claude-task.log 2>&1
And set up log rotation so the file doesn’t grow unbounded:
# In /etc/logrotate.d/claude-tasks
/var/log/claude-task.log {
daily
rotate 7
compress
missingok
}
Limitations to Know Before Relying on /loop
The /loop command is useful, but it has real constraints. Understanding them upfront prevents broken automations and unexpected costs.
Session Dependency
The most significant limitation: /loop tasks die when the session dies. If your terminal closes, the connection drops, or the Claude Code process exits for any reason, the loop stops. This makes it unsuitable for tasks that need guaranteed execution over long timespans without session management infrastructure.
For anything critical, supplement /loop with system cron or a process manager like pm2 or supervisor.
Context Accumulation
Claude Code sessions accumulate context as they run. Over many loop cycles, the conversation history grows, which affects both the quality of responses (earlier context can crowd out more relevant recent context) and token costs (you’re paying for all that accumulated context on each new call).
For long-running loops, periodically running /compact can help manage this. Alternatively, configure your loop to use a fresh context anchor each time rather than relying on accumulated session history.
API Costs at Scale
Every loop cycle consumes tokens — the prompt you write, the context Claude reads, the response it generates, and any tool calls it makes. At a short interval with a complex task, this adds up quickly.
Before setting a tight interval, estimate your per-cycle cost using /cost after a manual run, then multiply by the number of cycles per day. A task that costs $0.05 per run doesn’t sound like much until you’re running it every 5 minutes: that’s $14.40/day.
Match your interval to the actual value the task generates. Hourly is usually enough for monitoring tasks. Daily is appropriate for summaries. Real-time or minute-level polling is rarely worth the expense.
Tool Permissions and Safety
Claude Code’s permission model requires you to grant access to tools explicitly. If a loop task tries to use a tool that isn’t permitted — like writing files, running shell commands, or making network requests — it will either stop and ask for confirmation (which breaks unattended operation) or fail silently.
Audit your loop tasks with --dangerously-skip-permissions only if you fully understand what permissions you’re granting and trust the prompt completely. For most recurring tasks, it’s better to be explicit about what tools are enabled.
Output Reliability Over Long Runs
Claude’s responses aren’t deterministic. The same prompt, run twice, can produce different output — different formatting, different level of detail, different conclusions. For tasks where you need consistent, machine-parseable output, prompt for a specific output format explicitly:
/loop "check for deprecated imports and output ONLY a JSON array of file paths, no other text" --interval 1h
This reduces variability and makes downstream processing of the output more reliable.
No Native Alerting
The /loop command doesn’t have built-in alerting. If it finds a problem, it outputs to your terminal. You have to be watching — or have set up log monitoring separately — to catch issues.
For actual alerting, combine /loop’s output with external tools: pipe to a script that sends a Slack message, email, or push notification when specific keywords appear in the output.
Running Scheduled AI Workflows Without Terminal Complexity
If the session-dependency and infrastructure requirements of Claude Code’s /loop command feel like too much for what you need, there’s a more direct path to scheduled AI automation: building the recurring task as a background agent that runs independently of your terminal.
Where MindStudio Fits
MindStudio is a no-code platform for building and deploying AI agents. One of its core agent types is background agents — workflows that run on a defined schedule, completely independent of any active session or terminal process.
Where Claude Code’s /loop is a session-level construct that stops when you close your terminal, a MindStudio scheduled agent runs server-side on whatever cadence you set. You build it once, deploy it, and it runs — whether your laptop is open or not.
This is the better fit when:
- You need guaranteed execution (not contingent on a running terminal session)
- Your scheduled task involves non-code workflows — sending emails, updating a spreadsheet, posting to Slack, pulling from a CRM
- You want to trigger the same automated task for multiple team members or projects without each person managing their own Claude Code setup
- You’re not a developer and don’t want to manage crontabs, shell scripts, and session persistence
A Concrete Example
Say you want a Monday morning summary of your team’s Notion workspace changes, delivered to Slack. In Claude Code, that would require: a shell script, cron setup, a Notion API integration, a Slack API integration, error handling, and authentication management.
In MindStudio, you connect Notion and Slack, write a prompt for the summary, set it to run at 8 AM Monday, and deploy. The 1,000+ pre-built integrations handle the API work; you handle the logic.
For developers already working in Claude Code’s terminal environment, /loop is the lighter-weight option for code-adjacent automation. For anything that touches business tools, team workflows, or needs to run reliably without process management, MindStudio’s scheduled agents are the more practical choice.
You can start building on MindStudio for free at mindstudio.ai.
Frequently Asked Questions
Does the /loop command persist after I close my terminal?
No. The /loop command is tied to your Claude Code session. When you close the terminal or the process exits, the loop stops. For persistent scheduling that survives terminal closure, use system cron to run claude -p "your prompt" on a schedule, or use a terminal multiplexer like tmux or screen to keep the session alive.
Can I run multiple /loop tasks simultaneously in one session?
Claude Code can register multiple loop tasks in a single session, but they run sequentially rather than in parallel. If one task takes longer than expected, it can delay the next scheduled cycle. For truly concurrent recurring tasks, run separate Claude Code processes in separate terminal sessions.
How do I cancel a running /loop task?
Use /loop --cancel to stop the currently registered loop. If you have multiple loops registered, you may need to specify which one to cancel by its ID or by name, depending on how the command is structured in your version of Claude Code. You can also just end the session entirely to stop all active loops.
What happens if Claude encounters an error during a /loop cycle?
By default, Claude Code will report the error in the session output and attempt the next scheduled cycle. It doesn’t automatically retry the failed cycle or alert you externally. For tasks where failure needs attention, build error-checking into the prompt itself (“if this command fails, output the string ERROR followed by the reason”) and set up external log monitoring to catch it.
Is there a limit to how short the interval can be?
There’s no hard-coded minimum interval documented, but running loops at very short intervals (under a minute) will hit Anthropic’s API rate limits quickly and generate substantial costs. Anthropic enforces per-minute and per-day token limits depending on your plan tier. Check your current rate limits in the Anthropic console before setting aggressive intervals.
Can /loop tasks trigger actions outside Claude Code, like sending emails or posting to Slack?
Not directly. Claude Code’s tool set includes shell execution, file operations, and web browsing — but not native integrations with external services like Slack or email. You can work around this by having Claude generate a shell command that calls an external script or uses curl to hit a webhook, but this requires setup on your end. If you need recurring tasks that natively integrate with business tools, a platform like MindStudio is a more direct path.
Does using /loop affect how much context Claude Code has available?
Yes. Each cycle runs within the existing session context, which grows over time as loop output accumulates. This can eventually crowd out relevant context and increase per-cycle token costs. Running /compact periodically compresses session history to manage this. For long-running loops, consider whether the accumulated context is actually useful or whether a fresh session for each cycle would produce better results.
Key Takeaways
- The Claude Code
/loopcommand schedules prompts to run automatically at set intervals, functioning like an in-session cron job without requiring crontab setup. - It’s process-bound: loops stop when the session ends, so for persistent scheduling, pair
/loopwithtmux/screenor use system cron with theclaude -pnon-interactive flag. - The command is well-suited for code quality monitoring, test analysis, commit summaries, dependency checks, and documentation drift detection — tasks that repeat and benefit from automation.
- API costs scale with loop frequency. Estimate per-cycle cost before setting short intervals and match cadence to the actual value the task generates.
- For scheduled AI workflows that need to survive terminal closure, integrate with business tools, or run reliably across a team, MindStudio’s background agents offer a more managed path.
If you’re running recurring AI tasks and spending more time managing infrastructure than getting value from the automation, take a look at what MindStudio makes possible — you can have a scheduled agent running in well under an hour, no terminal management required.