⏰ Complete Claude Code × Cron Automation Guide - Streamline Tasks with Scheduled Execution¶
🎯 Overview¶
Combining Claude Code with cron enables complete automation of development tasks. This guide covers practical implementation methods from cron scheduling configuration to actual operation.
Current Environment as of February 2026
- Claude Code v2.0+: Compaction feature prevents context overflow even in long-running cron sessions
- Claude Opus 4.6: Agent teams capability, 1M context beta, adaptive thinking
- Hooks Integration: 14 hook event types enable automated error notification and log processing during cron execution
- Non-interactive Execution: Use
--dangerously-skip-permissionsflag or allowlists in.claude/settings.jsonfor permission control
📊 Benefits of Automation¶
🚀 Efficiency Gains
- Development Speed: 3-5x improvement
- Manual Work Reduction: Over 80% reduction
- Quality Improvement: Quality stabilization through consistent processing
- Operational Load: Significant reduction
🛠️ Basic Setup¶
1. Preparing Claude Code Environment¶
# Verify Claude Code installation
claude --version
# Authentication setup (if not configured)
claude auth login
# Non-interactive permission configuration (use one of the following)
# Method 1: --dangerously-skip-permissions flag (specify at script execution time)
# Skips all permission prompts during cron execution
claude --dangerously-skip-permissions -p "Execute task"
# Method 2: Configure allowlist in .claude/settings.json (recommended)
# More secure as you explicitly specify allowed tools/commands
cat << 'SETTINGS' > .claude/settings.json
{
"permissions": {
"allow": [
"Bash(npm test*)",
"Bash(npx eslint*)",
"Bash(npx tsc*)",
"Read",
"Write"
]
}
}
SETTINGS
Deprecated: claude config set auto_approve true
The claude config set auto_approve true command from older versions has been deprecated. Please migrate to one of the methods above.
2. Cron Job Configuration¶
# Edit crontab
crontab -e
# Basic scheduled execution examples
# Code quality check every day at 9 AM (-p passes prompt directly)
0 9 * * * cd /path/to/project && claude --dangerously-skip-permissions -p "Check code quality and create a report"
# Hourly execution (test automation)
0 * * * * cd /path/to/project && claude --dangerously-skip-permissions -p "Run tests and notify results to Slack"
# Weekday mornings (review automation)
0 8 * * 1-5 cd /path/to/project && claude --dangerously-skip-permissions -p "Review yesterday's changes and create PR comments"
🔧 Practical Automation Patterns¶
Pattern 1: Code Quality Management¶
#!/bin/bash
# ~/scripts/claude-quality-check.sh
PROJECT_PATH="/path/to/your/project"
REPORT_PATH="/tmp/quality-report-$(date +%Y%m%d).txt"
cd "$PROJECT_PATH"
# Execute quality check with Claude Code (--dangerously-skip-permissions for non-interactive mode)
claude --dangerously-skip-permissions -p "
Check the code quality of the entire project and analyze the following:
1. Fix ESLint errors and warnings
2. Resolve TypeScript type errors
3. Security vulnerability check
4. Performance improvement suggestions
5. Duplicate code detection
Create a report in Markdown format with the results.
" > "$REPORT_PATH" 2>&1
# Slack notification (optional)
if command -v slack-cli &> /dev/null; then
slack-cli -t "daily-reports" -m "Code quality report completed: $REPORT_PATH"
fi
Cron Configuration¶
# Run quality check every day at 9 AM
0 9 * * * /home/user/scripts/claude-quality-check.sh
Pattern 2: Automated Testing & Deployment¶
#!/bin/bash
# ~/scripts/claude-test-deploy.sh
PROJECT_PATH="/path/to/your/project"
LOG_FILE="/var/log/claude-deploy-$(date +%Y%m%d-%H%M).log"
cd "$PROJECT_PATH"
# Check for Git changes
if git diff-index --quiet HEAD --; then
echo "No changes - skipping" >> "$LOG_FILE"
exit 0
fi
# Automated test execution with Claude Code
claude --dangerously-skip-permissions -p "
Execute automated testing and deployment with the following steps:
1. Run the full test suite
2. Analyze and fix causes of test failures
3. Run lint/typecheck and apply fixes
4. Execute and verify build
5. Deploy only on success
Log detailed results for each step.
If an error occurs, stop processing and report detailed causes.
" >> "$LOG_FILE" 2>&1
# Email results (optional)
if [ $? -eq 0 ]; then
echo "Deploy success: $(date)" | mail -s "Deploy Success" admin@example.com
else
echo "Deploy failed: $(date)" | mail -s "Deploy Failed" admin@example.com
fi
Cron Configuration¶
# Automated deployment on weekday evenings
0 22 * * 1-5 /home/user/scripts/claude-test-deploy.sh
Pattern 3: Periodic Report Generation¶
#!/bin/bash
# ~/scripts/claude-weekly-report.sh
PROJECT_PATH="/path/to/your/project"
REPORT_DIR="/reports/weekly"
WEEK=$(date +%Y-W%U)
mkdir -p "$REPORT_DIR"
cd "$PROJECT_PATH"
# Generate weekly report
claude --dangerously-skip-permissions -p "
Create a comprehensive report on last week's development activities:
## 📊 Development Statistics
- Commit count and contributor analysis
- Code change volume (added/deleted lines)
- File change frequency analysis
## 🐛 Quality Analysis
- New bugs and their fix status
- Test coverage changes
- Performance metrics
## 🚀 Feature Development
- New feature implementation status
- Ongoing features and completion schedules
- Technical challenges and solutions
## 📋 Next Week's Plan
- Priority task suggestions
- Technical improvement items
- Resource allocation recommendations
Make it visually understandable using Markdown tables and graphs.
" > "$REPORT_DIR/report-$WEEK.md"
Cron Configuration¶
# Generate report every Monday at 8 AM
0 8 * * 1 /home/user/scripts/claude-weekly-report.sh
🔒 Security Configuration¶
Secure Environment Variable Management¶
# ~/.claude-env
export CLAUDE_API_KEY="your_api_key_here"
export PROJECT_PATH="/secure/path/to/project"
export NOTIFICATION_WEBHOOK="your_webhook_url"
# Permission settings
chmod 600 ~/.claude-env
Loading Environment in Cron Scripts¶
#!/bin/bash
# Load secure environment configuration
source ~/.claude-env
# Execute Claude Code
cd "$PROJECT_PATH"
claude --dangerously-skip-permissions -p "Execute secure processing"
📋 Advanced Configuration Examples¶
Conditional Execution¶
#!/bin/bash
# ~/scripts/claude-smart-automation.sh
PROJECT_PATH="/path/to/project"
cd "$PROJECT_PATH"
# Check for Git changes
CHANGES=$(git diff --name-only HEAD~1 HEAD | wc -l)
if [ "$CHANGES" -gt 10 ]; then
# Detailed check for large changes
claude --dangerously-skip-permissions -p "
Large-scale changes detected. Execute the following:
1. Run full test suite
2. Security audit
3. Performance testing
4. Detailed code review
"
elif [ "$CHANGES" -gt 0 ]; then
# Lightweight check for small changes
claude --dangerously-skip-permissions -p "
Minor changes detected. Execute the following:
1. Run related tests
2. Lint check
3. Basic code review
"
else
echo "No changes - skipping"
fi
Load Balancing Support¶
#!/bin/bash
# Parallel processing of multiple projects
PROJECTS=("/project1" "/project2" "/project3")
MAX_PARALLEL=3
process_project() {
local project_path=$1
cd "$project_path"
claude --dangerously-skip-permissions -p "
Execute project health check:
1. Check for dependency updates
2. Security updates
3. Performance optimization suggestions
"
}
# Parallel execution
for project in "${PROJECTS[@]}"; do
((i=i%MAX_PARALLEL)); ((i++==0)) && wait
process_project "$project" &
done
wait
Hooks Integration: Automated Error Notification for Cron¶
v2.0 Hooks Integration
With Claude Code v2.0's Hooks feature, you can automatically detect errors during cron execution and send notifications to Slack or email.
# Add Hook configuration to .claude/settings.json
cat << 'SETTINGS' > .claude/settings.json
{
"permissions": {
"allow": [
"Bash(npm test*)",
"Bash(npx eslint*)",
"Read",
"Write"
]
},
"hooks": {
"on_error": {
"command": "/home/user/scripts/notify-error.sh"
}
}
}
SETTINGS
#!/bin/bash
# ~/scripts/notify-error.sh - Error notification script called by Hooks
ERROR_MSG="${1:-Unknown error}"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
# Slack Webhook notification
curl -s -X POST "$NOTIFICATION_WEBHOOK" \
-H 'Content-Type: application/json' \
-d "{\"text\": \"[CRON ERROR] ${TIMESTAMP}: ${ERROR_MSG}\"}"
📊 Monitoring and Log Management¶
Log Rotation Configuration¶
# /etc/logrotate.d/claude-automation
/var/log/claude-*.log {
daily
rotate 30
compress
delaycompress
missingok
notifempty
sharedscripts
postrotate
# Post-rotation processing
systemctl reload rsyslog > /dev/null 2>&1 || true
endscript
}
Execution Status Monitoring¶
#!/bin/bash
# ~/scripts/claude-health-check.sh
HEALTH_LOG="/var/log/claude-health.log"
ALERT_THRESHOLD=5
# Count failures
FAILURES=$(grep -c "ERROR\|FAILED" "$HEALTH_LOG" | tail -1)
if [ "$FAILURES" -gt "$ALERT_THRESHOLD" ]; then
# Send alert
echo "Claude automation failures: $FAILURES" | \
mail -s "Claude Automation Alert" admin@example.com
fi
🚨 Troubleshooting¶
Common Issues and Solutions¶
1. Permission Errors¶
# PATH differs when running in cron
# Explicitly set environment variables in crontab
PATH=/usr/local/bin:/usr/bin:/bin
SHELL=/bin/bash
0 9 * * * cd /project && /usr/local/bin/claude --dangerously-skip-permissions -p "Execute task"
2. Claude Code Authentication Issues¶
# Check authentication information
claude auth status
# Re-authenticate (if necessary)
claude auth login --force
# Check configuration file
cat ~/.claude/config.json
3. Out of Memory Errors¶
# Limit memory usage
ulimit -v 2097152 # 2GB limit
# Execute Claude
claude --dangerously-skip-permissions -p "Split into lightweight tasks and execute"
Memory Efficiency with v2.0 Compaction
Claude Code v2.0's Compaction feature is ideal for long-running cron tasks. When the context window fills up, it automatically summarizes and compresses content, greatly reducing the context overflow errors that were common in previous versions. This enables stable execution of time-consuming tasks such as large codebase analysis and report generation.
Debug Configuration¶
#!/bin/bash
# Script with debug mode
set -euo pipefail # Stop on error
set -x # Display command execution
# Log output configuration
exec 1> >(tee -a /var/log/claude-debug.log)
exec 2> >(tee -a /var/log/claude-debug.log >&2)
echo "$(date): Claude automation starting"
# Execute Claude
claude --dangerously-skip-permissions -p "Debug task"
echo "$(date): Claude automation completed"
📈 Performance Optimization¶
Batch Processing Efficiency¶
#!/bin/bash
# Batch processing optimization
# Execute multiple tasks in a single Claude invocation
claude --dangerously-skip-permissions -p "
Execute the following tasks efficiently in batch:
## Task List
1. Run and fix ESLint
2. Resolve TypeScript errors
3. Run tests
4. Update documentation
5. Update package dependencies
Report results for each task progressively,
and provide detailed resolution methods if errors occur.
"
Resource Usage Optimization¶
# Limit CPU usage
nice -n 10 claude --dangerously-skip-permissions -p "Heavy processing task"
# Monitor memory usage
while true; do
MEM_USAGE=$(ps aux | grep claude | awk '{sum+=$6} END {print sum/1024}')
if (( $(echo "$MEM_USAGE > 1000" | bc -l) )); then
echo "Memory usage high: ${MEM_USAGE}MB"
# Adjust processing as needed
fi
sleep 30
done &
🔗 Related Links¶
- ⚡ Claude Code Auto-Execution Guide
- 🐳 Complete Claude Code Docker Guide
- 🎯 Claude Code Control Best Practices
💡 Summary¶
The combination of Claude Code x Cron enables complete automation of development workflows. With v2.0's Compaction feature improving stability for long-running tasks and Hooks integration enabling automated error notifications, you can build a more robust automation environment. With proper configuration and troubleshooting knowledge, you can significantly improve development efficiency.
🎯 Next Steps
- Start with basic cron jobs
- Gradually add complex automation
- Establish monitoring and logging systems
- Strengthen security configuration
- Automate error notifications with Hooks integration