๐ Claude Code + Cron Automation Complete Guide 2025 - Scheduled Execution & Scheduling Implementation¶
By integrating Claude Code with Cron, you can build advanced automation systems with scheduled execution and scheduling. This guide explains practical automation scenarios through to advanced operations in a step-by-step manner.
๐ Table of Contents¶
- ๐ฏ Basic Concepts and Preparation
- โก Basic Cron Integration
- ๐ ๏ธ Practical Automation Patterns
- ๐ Advanced Operations Techniques
- โ ๏ธ Troubleshooting
๐ฏ Basic Concepts and Preparation¶
Benefits of Combining Claude Code and Cron¶
Value of Automation
- Scheduled Execution: Automate daily, weekly, monthly periodic tasks
- Code Generation: Regular code updates and refactoring
- Monitoring & Maintenance: Periodic system health checks
- Data Processing: Automate log analysis and report generation
Prerequisites¶
# Check Cron
crontab -l
# Verify Claude Code installation
claude --version
# Create working directory
mkdir -p ~/claude-automation/{scripts,logs,config}
cd ~/claude-automation
# Start Cron service in WSL
sudo service cron start
# Configure auto-start
sudo systemctl enable cron
# Check Claude Code
claude --version
โก Basic Cron Integration¶
1. Simple Scheduled Execution Script¶
daily-code-review.sh
#!/bin/bash
# Claude Code + Cron basic execution script
LOG_FILE="$HOME/claude-automation/logs/daily-$(date +%Y%m%d).log"
PROJECT_PATH="$HOME/projects/my-app"
echo "=== Claude Code Daily Review: $(date) ===" >> "$LOG_FILE"
cd "$PROJECT_PATH" || exit 1
# Execute code review with Claude Code
claude code . --prompt "Check overall project code quality and output improvement suggestions" \
--output "$HOME/claude-automation/logs/review-$(date +%Y%m%d).md" \
>> "$LOG_FILE" 2>&1
echo "=== Review Completed: $(date) ===" >> "$LOG_FILE"
2. Crontab Configuration Examples¶
# Edit crontab
crontab -e
# Configuration examples
# Daily code review at 9:00 AM
0 9 * * * /home/user/claude-automation/scripts/daily-code-review.sh
# Full scan every Monday
0 10 * * 1 /home/user/claude-automation/scripts/weekly-scan.sh
# Generate report on the 1st of each month
0 8 1 * * /home/user/claude-automation/scripts/monthly-report.sh
๐ ๏ธ Practical Automation Patterns¶
Pattern 1: Automatic Backup + Code Analysis¶
backup-and-analyze.sh
#!/bin/bash
BACKUP_DIR="$HOME/backups/$(date +%Y%m%d)"
PROJECT_DIR="$HOME/projects/webapp"
LOG_FILE="$HOME/claude-automation/logs/backup-$(date +%Y%m%d).log"
# Create backup
mkdir -p "$BACKUP_DIR"
rsync -av "$PROJECT_DIR/" "$BACKUP_DIR/" >> "$LOG_FILE"
# Analyze changes with Claude Code
cd "$PROJECT_DIR" || exit 1
claude code . --prompt "
Analyze changes since yesterday and output:
1. Overview of added features
2. Potential security risks
3. Performance improvement suggestions
4. Test coverage improvements
" --output "$HOME/claude-automation/reports/daily-analysis-$(date +%Y%m%d).md" \
>> "$LOG_FILE" 2>&1
Pattern 2: Dependency Monitoring & Updates¶
dependency-monitor.sh
#!/bin/bash
PROJECT_DIR="$HOME/projects/webapp"
ALERT_EMAIL="admin@company.com"
cd "$PROJECT_DIR" || exit 1
# Check dependencies with Claude Code
ANALYSIS_RESULT=$(claude code . --prompt "
Analyze dependencies in package.json and check:
1. Packages with security vulnerabilities
2. Packages with significant available updates
3. Deprecated packages
4. List of recommended safe updates
Output results in JSON format.
" --format json)
# Send email notification for high-severity issues
if echo "$ANALYSIS_RESULT" | jq -r '.security_issues[]' | grep -q "critical"; then
echo "$ANALYSIS_RESULT" | mail -s "Critical Security Issues Detected" "$ALERT_EMAIL"
fi
# Save report
echo "$ANALYSIS_RESULT" > "$HOME/claude-automation/reports/dependency-$(date +%Y%m%d).json"
Pattern 3: Automatic Refactoring¶
auto-refactor.sh
#!/bin/bash
PROJECT_DIR="$HOME/projects/api-server"
BRANCH_NAME="auto-refactor-$(date +%Y%m%d)"
cd "$PROJECT_DIR" || exit 1
# Create new branch
git checkout -b "$BRANCH_NAME"
# Execute refactoring with Claude Code
claude code . --prompt "
Refactor code according to the following criteria:
1. Remove duplicate code
2. Split functions (functions exceeding 100 lines)
3. Improve variable names
4. Add comments
5. Improve TypeScript type definitions
Output list of changed files and reasons for changes.
" --execute --output "refactor-log-$(date +%Y%m%d).md"
# Commit and push if there are changes
if git diff --quiet; then
echo "No changes to commit"
git checkout main
git branch -d "$BRANCH_NAME"
else
git add .
git commit -m "๐ค Auto-refactor: $(date +%Y-%m-%d)
Automated refactoring by Claude Code:
- Code duplication removal
- Function decomposition
- Variable naming improvements
- Type definition enhancements"
git push origin "$BRANCH_NAME"
# Create pull request (using GitHub CLI)
gh pr create --title "๐ค Automated Refactoring $(date +%Y-%m-%d)" \
--body "Automated code improvements by Claude Code + Cron" \
--base main --head "$BRANCH_NAME"
fi
๐ Advanced Operations Techniques¶
1. Conditional Execution System¶
conditional-execution.sh
#!/bin/bash
PROJECT_DIR="$HOME/projects/webapp"
CONFIG_FILE="$HOME/claude-automation/config/settings.json"
# Load configuration
LAST_COMMIT=$(jq -r '.last_processed_commit' "$CONFIG_FILE")
CURRENT_COMMIT=$(cd "$PROJECT_DIR" && git rev-parse HEAD)
# Execute only if there are new commits
if [ "$LAST_COMMIT" != "$CURRENT_COMMIT" ]; then
echo "New commits detected, running analysis..."
cd "$PROJECT_DIR" || exit 1
# Get changed files
CHANGED_FILES=$(git diff --name-only "$LAST_COMMIT" HEAD)
# Analyze changes with Claude Code
claude code . --prompt "
The following files were changed:
$CHANGED_FILES
Analyze the changes and output:
1. Impact scope assessment
2. Identification of required tests
3. Pre-deployment checklist
4. Potential risk assessment
" --output "$HOME/claude-automation/reports/change-analysis-$(date +%Y%m%d-%H%M).md"
# Update configuration
jq --arg commit "$CURRENT_COMMIT" '.last_processed_commit = $commit' "$CONFIG_FILE" > tmp.json
mv tmp.json "$CONFIG_FILE"
else
echo "No new commits, skipping analysis"
fi
2. Parallel Execution and Locking Mechanism¶
parallel-safe-execution.sh
#!/bin/bash
LOCK_FILE="/tmp/claude-automation.lock"
MAX_PARALLEL=3
# Acquire lock
exec 200>"$LOCK_FILE"
if ! flock -n 200; then
echo "Another instance is running, exiting..."
exit 1
fi
# Parallel processing function
run_analysis() {
local project_path="$1"
local analysis_type="$2"
echo "Starting $analysis_type for $project_path"
cd "$project_path" || return 1
claude code . --prompt "$analysis_type analysis" \
--output "$HOME/claude-automation/reports/${analysis_type}-$(basename "$project_path")-$(date +%Y%m%d).md" &
local pid=$!
echo "$pid" >> "$HOME/claude-automation/pids.tmp"
return 0
}
# Process multiple projects in parallel
PROJECTS=(
"$HOME/projects/frontend"
"$HOME/projects/backend"
"$HOME/projects/mobile-app"
)
for project in "${PROJECTS[@]}"; do
run_analysis "$project" "security" &
# Limit parallel count
job_count=$(jobs -r | wc -l)
if [ "$job_count" -ge $MAX_PARALLEL ]; then
wait -n # Wait for one job to complete
fi
done
# Wait for all jobs to complete
wait
# Release lock
flock -u 200
3. Error Handling and Notifications¶
robust-automation.sh
#!/bin/bash
set -euo pipefail # Exit immediately on error
LOG_FILE="$HOME/claude-automation/logs/main-$(date +%Y%m%d).log"
ERROR_LOG="$HOME/claude-automation/logs/error-$(date +%Y%m%d).log"
WEBHOOK_URL="https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK"
# Error handler
error_handler() {
local line_no=$1
local error_code=$2
echo "Error on line $line_no: exit code $error_code" | tee -a "$ERROR_LOG"
# Slack notification
curl -X POST -H 'Content-type: application/json' \
--data "{\"text\":\"Claude Code automation failed: Line $line_no, Code $error_code\"}" \
"$WEBHOOK_URL"
# Send logs
tail -50 "$LOG_FILE" | mail -s "Claude Code Automation Error" admin@company.com
exit "$error_code"
}
trap 'error_handler ${LINENO} $?' ERR
# Main processing
{
echo "=== Starting Claude Code automation: $(date) ==="
# Execute various checks
run_security_scan
run_performance_analysis
run_code_quality_check
echo "=== Automation completed successfully: $(date) ==="
# Success notification
curl -X POST -H 'Content-type: application/json' \
--data '{"text":"โ
Claude Code automation completed successfully"}' \
"$WEBHOOK_URL"
} 2>&1 | tee -a "$LOG_FILE"
๐ Monitoring & Metrics Collection¶
Automatic Execution Statistics Aggregation¶
metrics-collector.sh
#!/bin/bash
METRICS_FILE="$HOME/claude-automation/metrics/$(date +%Y%m).json"
LOG_DIR="$HOME/claude-automation/logs"
# Aggregate today's execution statistics
TODAY=$(date +%Y%m%d)
TODAY_LOGS=$(find "$LOG_DIR" -name "*$TODAY*" -type f)
TOTAL_EXECUTIONS=$(echo "$TODAY_LOGS" | wc -l)
SUCCESSFUL_RUNS=$(grep -l "completed successfully" $TODAY_LOGS | wc -l)
FAILED_RUNS=$((TOTAL_EXECUTIONS - SUCCESSFUL_RUNS))
# Update metrics
jq --arg date "$TODAY" \
--arg total "$TOTAL_EXECUTIONS" \
--arg success "$SUCCESSFUL_RUNS" \
--arg failed "$FAILED_RUNS" \
'.daily_stats += [{
date: $date,
total_executions: ($total | tonumber),
successful_runs: ($success | tonumber),
failed_runs: ($failed | tonumber),
success_rate: (($success | tonumber) / ($total | tonumber) * 100)
}]' "$METRICS_FILE" > tmp.json && mv tmp.json "$METRICS_FILE"
# Generate weekly report (Mondays only)
if [ "$(date +%u)" = "1" ]; then
claude code . --prompt "
Analyze metrics file $METRICS_FILE and
create a performance report for the automation system over the past week:
1. Success rate trends
2. Failure pattern analysis
3. Improvement suggestions
" --output "$HOME/claude-automation/reports/weekly-performance-$(date +%Y%m%d).md"
fi
โ ๏ธ Troubleshooting¶
1. Common Issues and Solutions¶
Environment Variable Issues in Cron Execution
# Cron has minimal environment variables
# Explicitly set PATH in the script
#!/bin/bash
export PATH="/usr/local/bin:/usr/bin:/bin:$HOME/.local/bin"
export NODE_PATH="/usr/local/lib/node_modules"
# Verify environment before executing Claude Code
which claude || exit 1
Permission Errors
# Set log directory permissions
chmod 755 "$HOME/claude-automation"
chmod 644 "$HOME/claude-automation/logs"/*
# Set script execution permissions
chmod +x "$HOME/claude-automation/scripts"/*.sh
2. Debugging Cron Script¶
debug-cron.sh
#!/bin/bash
DEBUG_LOG="$HOME/claude-automation/debug-$(date +%Y%m%d-%H%M).log"
{
echo "=== Debug Info: $(date) ==="
echo "User: $(whoami)"
echo "Working Directory: $(pwd)"
echo "PATH: $PATH"
echo "Environment:"
env | sort
echo ""
echo "Claude Code Version:"
claude --version || echo "Claude not found in PATH"
echo ""
echo "Available Commands:"
which git || echo "git not found"
which node || echo "node not found"
which npm || echo "npm not found"
echo ""
echo "=== Running Actual Script ==="
} >> "$DEBUG_LOG" 2>&1
# Execute actual script (debug mode)
"$HOME/claude-automation/scripts/daily-code-review.sh" >> "$DEBUG_LOG" 2>&1
3. Log Rotation¶
log-rotation.sh
#!/bin/bash
LOG_DIR="$HOME/claude-automation/logs"
ARCHIVE_DIR="$HOME/claude-automation/archives"
RETENTION_DAYS=30
# Archive logs older than 30 days
find "$LOG_DIR" -name "*.log" -mtime +$RETENTION_DAYS -exec mv {} "$ARCHIVE_DIR/" \;
# Delete files in archive directory older than 90 days
find "$ARCHIVE_DIR" -name "*.log" -mtime +90 -delete
# Compress to save storage
find "$ARCHIVE_DIR" -name "*.log" -mtime +7 -exec gzip {} \;
๐ง Advanced Configuration Examples¶
Fully Integrated Crontab¶
# Complete automation crontab configuration example
# Every 15 minutes: High-priority security check
*/15 * * * * /home/user/claude-automation/scripts/security-monitor.sh
# Every hour: Lightweight quality check
0 * * * * /home/user/claude-automation/scripts/hourly-quality-check.sh
# Daily at 9:00 AM: Full code review
0 9 * * * /home/user/claude-automation/scripts/daily-full-review.sh
# Daily at 11:00 PM: Backup + analysis
0 23 * * * /home/user/claude-automation/scripts/backup-and-analyze.sh
# Every Monday morning: Weekly report generation
0 8 * * 1 /home/user/claude-automation/scripts/weekly-report.sh
# 1st of each month: Large-scale dependency check
0 6 1 * * /home/user/claude-automation/scripts/monthly-dependency-audit.sh
# Daily at midnight: Log rotation
0 2 * * * /home/user/claude-automation/scripts/log-rotation.sh
๐ Best Practices for Operational Optimization¶
- Gradual Introduction: Start with lightweight tasks
- Monitoring System: Set up metrics collection and alerts
- Redundancy: Execute critical tasks at multiple time slots
- Security: Proper handling of sensitive information
- Performance: Regular monitoring of resource usage
The combination of Claude Code + Cron enables continuous code quality improvement and operational automation. Introduce gradually and optimize for your team's development workflow.