Building Scheduled AI Agents with Claude Code
Claude Code now handles scheduled tasks natively. Here's how to set up fully autonomous AI agents that run on a schedule, self-correct when they fail, and require zero human babysitting. The interesting part? You don't need a specialized orchestration platform to pull this off.
Setting Up Your Environment
What You'll Need
Before diving in, make sure you have:
- Node.js 18 or higher — Claude Code runs on Node
- Claude Code installed —
npm install -g @anthropic-ai/claude-code - An Anthropic API key — Store it as
ANTHROPIC_API_KEYin your environment - A Unix-like system — Linux or macOS for cron-based scheduling (Windows users can use Task Scheduler or WSL)
Installation
npm install -g @anthropic-ai/claude-code
Verify the installation:
claude --version
Securing Your API Key
For scheduled agents, your API key needs to be accessible at runtime without manual entry. Store it safely:
ANTHROPIC_API_KEY="your-key-here"
For production systems, use a dedicated secrets manager:
- AWS Secrets Manager — Works seamlessly with EC2, Lambda, and ECS
- HashiCorp Vault — Multi-cloud provider support
- GitHub Actions Secrets — If running in CI/CD pipelines
- 1Password Secrets Automation — Great for team setups
Never hardcode keys directly in scripts or commit them to version control.
Using CLAUDE.md for Persistent Agent Instructions
One of the most powerful features for scheduled agents is the CLAUDE.md file. Place it in your project root (or at ~/.claude/CLAUDE.md for system-wide agent guidance), and Claude reads it automatically at the start of each session.
This is where you define the standing context your agent needs to function:
# Monitoring Agent Instructions
## Project Context
This is a Node.js API server. Logs are stored in ./logs/.
The database is PostgreSQL running on localhost:5432.
The API serves traffic on ports 3000 (staging) and 4000 (production).
## Agent Responsibilities
- You are a monitoring agent. Your job is to observe and report, not to make changes.
- When you find issues, write them to ./alerts/[timestamp].json
- Never modify files in ./src/ or ./config/
- If you find a critical issue, also append a summary to ./alerts/critical.log
## What "Critical" Means
- Error rate above 5% in the last hour
- Average response time above 2000ms
- Database connection failures
- Any 5xx errors from /api/payments endpoint
## Escalation
For critical alerts, run /scripts/notify-oncall.sh with the alert details.
For warnings, append to /alerts/warnings.log only.
Building Your First Scheduled Agent
Here's a detailed walkthrough of building a log-monitoring agent that runs hourly.
Step 1: Define Agent Scope
Before you write any configuration, be explicit about:
- What data the agent needs to access
- What decisions the agent makes
- What actions the agent takes
- How the agent reports results
In this example, the agent reads application logs, identifies errors from the last hour, and writes to an alert file if anything warrants attention.
Step 2: Write a Shell Wrapper Script
Create a script that invokes Claude Code:
#!/bin/bash
# /opt/agents/log-monitor.sh
# Load environment variables
source /etc/environment
# Set working directory — always use absolute paths in scheduled scripts
cd /var/www/myapp || { echo "Cannot navigate to project directory"; exit 1; }
# Generate a timestamp for this run
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
LOG_FILE="/var/log/agent-runs/monitor-${TIMESTAMP}.log"
echo "Agent run started: ${TIMESTAMP}" >> "$LOG_FILE"
# Run the agent
claude -p "
You are a log monitoring agent running an automated check.
Current time: ${TIMESTAMP}
Your task:
1. Read ./logs/app.log and ./logs/error.log
2. Find any lines with level ERROR or FATAL from the last 60 minutes
3. Categorize each issue by severity: critical, warning, or informational
4. If there are critical or warning issues, write a JSON file to ./alerts/${TIMESTAMP}.json with:
- timestamp
- severity
- affected_component
- error_message
- suggested_action
5. If everything looks healthy, write 'HEALTHY: ${TIMESTAMP}' to ./status/latest.txt
If you cannot read a log file, note that in your output and continue with what you can access.
" \\
--allowedTools "Bash,Read,Write" \\
--max-turns 15 \\
--output-format json \\
>> "$LOG_FILE" 2>&1
EXIT_CODE=$?
echo "Agent run completed with exit code: ${EXIT_CODE}" >> "$LOG_FILE"
# Alert if the agent itself failed
if [ $EXIT_CODE -ne 0 ]; then
/scripts/notify-team.sh "Agent log-monitor failed (exit code $EXIT_CODE). Check $LOG_FILE"
fi
A few key points here:
- Always use absolute paths. Working directories are unpredictable in scheduled contexts.
- Capture the exit code. Claude Code returns non-zero on failure.
- Include the current timestamp in your prompt. The agent won't know real-time unless you tell it.
- Log everything. You'll need those logs when debugging issues at 3am.
Step 3: Test Manually First
Run it by hand before scheduling:
chmod +x /opt/agents/log-monitor.sh
/opt/agents/log-monitor.sh
Check the output log for:
- Tool permission errors — Adjust
--allowedToolsif the agent can't access what it needs - Path issues — If the agent says files aren't found, check your working directory setup
- Prompt ambiguity — If the agent does something unexpected, your instructions need to be more specific
Iterate by refining your CLAUDE.md and prompt until behavior matches expectations.
Step 4: Add a Cron Job
Once the script runs correctly, schedule it:
crontab -e
Add your scheduling rules:
# Run log monitor every hour
0 * * * * /opt/agents/log-monitor.sh
# Run daily summary every morning at 7am
0 7 * * * /opt/agents/daily-summary.sh
# Run security scan every Sunday at 2am
0 2 * * 0 /opt/agents/security-scan.sh
Quick cron syntax reference:
┌───────────── minute (0–59)
│ ┌───────────── hour (0–23)
│ │ ┌───────────── day of month (1–31)
│ │ │ ┌───────────── month (1–12)
│ │ │ │ ┌───────────── day of week (0–6, Sunday=0)
│ │ │ │ │
* * * * * command
Use crontab.guru to validate scheduling expressions before deploying them.
Key Principles to Remember
Building reliable scheduled AI agents with Claude Code rests on a few core practices:
- Use
-pfor automation — Non-interactive mode is essential. Without it, scheduling is impossible. - CLAUDE.md holds your standing orders — Context, constraints, and escalation policies live there. Every scheduled run automatically inherits them.
- Write prompts with clear branching — Tell the agent what to do in each scenario, including when to escalate and when to do nothing.
- Design for retry — Agents will re-run after failure. Build tasks to be idempotent so retries don't create new problems.
- Monitor everything — Structured logs, exit code checks, and heartbeat monitoring are how you know your agents are working.
- Layer your defenses — OS-level permissions plus agent-level instructions are more trustworthy than either alone.
What's really powerful here is that Claude Code's reasoning ability combined with standard scheduling infrastructure gives you autonomous agents capable of handling real operational work — without needing a specialized orchestration platform or major infrastructure investment.
Related Articles
- 8 Effective Methods to Monitor Your Hard Drive Health and Catch Problems Early
- How to Fix the Task Host Window Blocking Windows Shutdown
- How to Restore a Windows System Using UEFI-Compatible .tib Ghost Files
- Understanding Mesh WiFi: How Does a Mesh Network System Actually Work?
- The 22 Best Tools for Creating Bootable USB Drives
