Skip to content

Claude Code Complete Guide

⏰ Claude Code × Cron Complete Automation Guide - Streamline Tasks with Scheduled Execution

TL;DR: Scheduling Claude Code with cron fully automates log monitoring, test execution, and periodic report generation. This guide starts with the basic pattern */30 * * * * claude -p "..." and covers error handling and log management.

Target readers: Linux/macOS users familiar with cron basics. Assumes Claude Code is already installed.

This article reflects August 2025 information

CLI commands (claude auth login, claude config set, etc.) may have changed in the current version. For the updated Cron automation guide, see Claude Code × Cron Complete Automation Guide (2025 Edition).

🎯 Overview

By combining Claude Code with cron, you can fully automate development tasks. This guide covers practical implementation methods, from setting up scheduled execution with cron to actual operations.

📊 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: Significantly reduced

🛠️ Basic Setup

1. Preparing the Claude Code Environment

# Verify Claude Code installation
claude --version

# Configure authentication (if not set)
claude auth login

# Set auto-approval (important)
claude config set auto_approve true

2. Cron Job Configuration

# Edit crontab
crontab -e

# Basic scheduled execution examples
# Daily code quality check at 9 AM
0 9 * * * cd /path/to/project && claude "Check code quality and create a report"

# Hourly execution (test automation)
0 * * * * cd /path/to/project && claude "Run tests and notify results to Slack"

# Weekday mornings (review automation)
0 8 * * 1-5 cd /path/to/project && claude "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
claude << 'EOF' > "$REPORT_PATH" 2>&1
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. Code duplication detection

Create the results as a report in Markdown format.
EOF

# 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 daily 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

# Automate test execution with Claude Code
claude << 'EOF' >> "$LOG_FILE" 2>&1
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 and fix lint/typecheck
4. Execute and verify build
5. Deploy only on success

Output detailed logs for each step.
If an error occurs, stop processing and report the detailed cause.
EOF

# Send result via email (optional)
if [ $? -eq 0 ]; then
    echo "Deployment successful: $(date)" | mail -s "Deploy Success" admin@example.com
else
    echo "Deployment failed: $(date)" | mail -s "Deploy Failed" admin@example.com
fi

Cron Configuration

# Automated deployment on weekday nights
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 << 'EOF' > "$REPORT_DIR/report-$WEEK.md"
Create a comprehensive report on last week's development activities:

## 📊 Development Statistics
- Commit count and contributor analysis
- Code change volume (lines added/deleted)
- File change frequency analysis

## 🐛 Quality Analysis
- New bugs and their fix status
- Test coverage changes
- Performance metrics

## 🚀 Feature Development
- Implementation status of new features
- Ongoing features and completion schedule
- Technical challenges and solutions

## 📋 Next Week's Plan
- Priority task suggestions
- Technical improvement items
- Resource allocation proposals

Make it visually clear using Markdown tables and charts.
EOF

Cron Configuration

# Generate report every Monday at 8 AM
0 8 * * 1 /home/user/scripts/claude-weekly-report.sh

🔒 Security Configuration

Secure Management of Environment Variables

# ~/.claude-env
export CLAUDE_API_KEY="your_api_key_here"
export PROJECT_PATH="/secure/path/to/project"
export NOTIFICATION_WEBHOOK="your_webhook_url"

# Set permissions
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 "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 << 'EOF'
    Large changes detected. Execute the following:
    1. Run the full test suite
    2. Security audit
    3. Performance testing
    4. Detailed code review
    EOF
elif [ "$CHANGES" -gt 0 ]; then
    # Lightweight check for small changes
    claude << 'EOF'
    Minor changes detected. Execute the following:
    1. Run related tests
    2. Lint check
    3. Basic code review
    EOF
else
    echo "No changes - skipping"
fi

Load Balancing Support

#!/bin/bash
# Parallel processing for multiple projects

PROJECTS=("/project1" "/project2" "/project3")
MAX_PARALLEL=3

process_project() {
    local project_path=$1
    cd "$project_path"

    claude << 'EOF'
    Execute project health check:
    1. Check for dependency updates
    2. Security updates
    3. Performance optimization suggestions
    EOF
}

# Parallel execution
for project in "${PROJECTS[@]}"; do
    ((i=i%MAX_PARALLEL)); ((i++==0)) && wait
    process_project "$project" &
done
wait

📊 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 "Execute task"

2. Claude Code Authentication Issues

# Check authentication status
claude auth status

# Re-authenticate (if necessary)
claude auth login --force

# Check configuration file
cat ~/.claude/config.json

3. Memory Shortage Errors

# Limit memory usage
ulimit -v 2097152  # 2GB limit

# Execute Claude
claude "Split into lightweight tasks and execute"

Debug Configuration

#!/bin/bash
# Script with debug mode

set -euo pipefail  # Stop on error
set -x             # Show 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 "Debug task"

echo "$(date): Claude automation completed"

📈 Performance Optimization

Batch Processing Optimization

#!/bin/bash
# Batch processing optimization

# Execute multiple tasks in one Claude call
claude << 'EOF'
Efficiently batch execute the following tasks:

## Task List
1. Run and fix ESLint
2. Resolve TypeScript errors
3. Run tests
4. Update documentation
5. Update package dependencies

Report the results of each task progressively,
and if an error occurs, provide a detailed solution.
EOF

Resource Usage Optimization

# Limit CPU usage
nice -n 10 claude "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 &

💡 Summary

The combination of Claude Code × Cron enables complete automation of development workflows. With proper configuration and troubleshooting knowledge, you can build a stable automation environment and significantly improve development efficiency.

🎯 Next Steps

  1. Start with basic cron jobs
  2. Gradually add more complex automation
  3. Establish monitoring and logging systems
  4. Strengthen security configuration