Routines: Scheduled Automation on Cloud Infrastructure
Routines are Claude Code's equivalent of cron jobs—they run on a schedule (daily, weekly, on demand) and execute tasks automatically. Unlike self-hosted cron, routines are managed by Claude: no infrastructure to maintain, built-in error handling, automatic retries, and audit logs included. This guide teaches how to define routines, handle failures, manage costs, and use them for real tasks: daily security scans, dependency audits, morning briefings, and weekly code reviews.
The mental model is simple: a routine = (task description + schedule). Claude handles scheduling, execution environment, and alerting. You write the task prompt once, set a schedule, and Claude runs it forever—or until you delete the routine. For event-driven automation that triggers on push or PRs rather than a schedule, see GitHub Actions with Claude Code; for in-process automation hooks that fire on tool calls, see the Claude Code hooks guide.
What Routines Are and How They Work
A routine is a scheduled Claude Code task that runs automatically at specified intervals. For example:
- Daily at 9 AM UTC: Run a security scan on the codebase.
- Every Monday 6 AM: Audit all open dependencies for known CVEs.
- Every 6 hours: Check if any integration tests are flaky and report.
When a routine's scheduled time arrives, Claude Code wakes up, executes your task in a new runner, captures the output, and posts results (via email, Slack, or GitHub). If the task fails, Claude automatically retries after a delay (e.g., 1 hour later); if it still fails, it alerts you.
Routines are separate from on-demand Claude Code runs. On-demand is when you manually invoke Claude via a command or PR. Routines are fire-and-forget: set them up once, and they run forever.
Quick reference
- Routines run in isolated runners; each routine execution is independent and has no state carryover.
- Execution context: routines have access to your repos and secrets (same as GitHub Actions).
- Concurrency: multiple routines can run simultaneously; each uses its own runner.
- Idempotency: design routines to be idempotent (safe to run multiple times); if a routine is triggered twice by mistake, results should be the same.
- Cost: routines are charged per execution; a daily routine = 30 executions/month, a weekly = ~4/month.
Remember this
A routine is a scheduled Claude Code task; when the scheduled time arrives, Claude wakes up, runs the task, captures output, and alerts you if it fails.
Schedule Syntax and Timezone Handling
Routines use cron syntax for scheduling. The format is:
1minute hour day-of-month month day-of-weekExamples:
- 0 9 * * * = Every day at 9:00 AM.
- 0 6 * * MON = Every Monday at 6:00 AM.
- 0 */6 * * * = Every 6 hours (0, 6, 12, 18 UTC).
- 30 14 15 * * = 15th of every month at 14:30 UTC.
Timezone handling: Cron times are in UTC by default. If your team is in PST (UTC-8), schedule at 17:00 UTC for 9:00 AM PST. To avoid confusion, always document the UTC time in comments.
When daylight saving time changes, UTC times don't shift (that's the point of UTC), but local time does. Use UTC in your cron to avoid surprises.
Quick reference
- Cron generator: use crontab.guru to visualize your schedule before saving.
- Special shortcuts: @daily (0 0 ), @weekly (0 0 0), @hourly (0 *).
- Minute granularity: routines support every 1 minute; can't do sub-minute schedules.
- Off-peak scheduling: schedule large tasks (long-running scans) at night or weekend to avoid peak hours.
- Avoid thundering herd: if multiple routines start at exactly the same time, stagger them by 5-10 minutes.
Remember this
Routines use cron syntax; schedule in UTC to avoid timezone confusion; use crontab.guru to verify schedules before saving.
Routine Templates for Common Tasks
Here are battle-tested templates for common routines:
1. Daily Security Scan
1Name: Daily Security Audit2Schedule: 0 9 * * * (9 AM UTC)3Task: Scan for hardcoded secrets, unvalidated input, outdated dependencies. Output a JSON report.2. Weekly Dependency Audit
1Name: Dependency Vulnerability Check2Schedule: 0 6 * * MON (Monday 6 AM UTC)3Task: Run npm audit (or cargo audit, pip audit). Report any high/critical CVEs. Auto-create PR to bump versions if patches exist.3. Morning Briefing
1Name: Team Standup Briefing2Schedule: 0 7 * * MON-FRI (7 AM UTC on weekdays)3Task: List open PRs older than 2 days, failed CI checks, open issues tagged "urgent". Post to Slack #standup.4. Weekly Code Quality Report
1Name: Code Quality Metrics2Schedule: 0 8 * * FRI (Friday 8 AM UTC)3Task: Calculate lines of code, test coverage %, cyclomatic complexity. Compare to last week. Post trends to Slack.5. Monthly Cost Report
1Name: Infrastructure Cost Audit2Schedule: 0 9 1 * * (1st of month, 9 AM UTC)3Task: Query cloud provider (AWS, GCP) for cost breakdown. Identify wasteful resources. Email report to finance.Quick reference
- Idempotent tasks: if re-run, should produce the same result; avoid side effects like 'increment counter'.
- Error tolerance: routine should handle missing files or temporary network issues gracefully.
- Notifications: specify where results go (Slack, email, GitHub issue) in the routine setup.
- Retention: old routine reports are archived; decide retention policy (90 days, 1 year).
- Versioning: if you update a routine's task prompt, older runs still use the old prompt; version control your prompts.
Remember this
Routine templates: security scans, dependency audits, briefings, metrics, cost reports; design for idempotency and clear output.
Monitoring Routine Execution and Status
Routines are autonomous, but you need visibility. Monitor via:
1. Dashboard: Claude Code console shows each routine's history (last run time, status, output). 2. Notifications: Configure alerts for failed routines (email, Slack, PagerDuty). 3. Logs: Every routine execution is logged; search by routine name, date, or status. 4. Metrics: Track routine success rate over time; alert if pass rate drops below 95%.
Example dashboard view: - Daily Security Audit: Last run 2 hours ago, Status ✅ PASS, 3 issues found. - Dependency Audit: Last run yesterday, Status ✅ PASS, no new CVEs. - Morning Briefing: Last run today 7 AM, Status ⚠️ RETRY (first attempt failed, retry at 8 AM).
If a routine fails, Claude provides the error message (e.g., "git clone failed: repo not accessible"). Review the error, fix the underlying issue (wrong credentials, repo deleted), and manually trigger a re-run. Subsequent scheduled runs should succeed.
Quick reference
- Success rate dashboard: visual indicator of routine health; alert if <95% success.
- Max retries: configure how many times Claude retries before giving up (default 3).
- Retry backoff: exponential backoff (1 hour, then 2 hours, then 4 hours) avoids retry storms.
- Dead letter queue: if a routine fails all retries, it's marked as dead; needs manual intervention.
- Export logs: download routine logs as CSV for analysis or compliance reporting.
Remember this
Monitor routine execution via dashboard, notifications, and logs; configure alerts for failures; track success rate to detect trends.
Error Handling and Automatic Retries
Routine tasks can fail for transient reasons (network hiccup, GitHub down, API rate limit). Claude handles this:
1. First attempt fails: Claude captures the error and schedules a retry. 2. Retry strategy: Exponential backoff—retry after 1 hour, then 2, then 4. 3. Max retries: By default 3 retries; configurable per routine. 4. Alert on final failure: If all retries fail, alert the owner (email, Slack). 5. Manual override: You can manually trigger a re-run from the dashboard.
Handling common errors: - Git auth failed: Verify SSH key or GitHub token hasn't expired; rotate if needed. - API rate limit: Routine hit rate limits (e.g., GitHub API). Add delay between requests; Claude can batch requests to reduce API calls. - Repo not found: Someone deleted the repo. Update routine with correct repo URL or delete the routine. - Timeout: Routine exceeded max runtime (e.g., 1-hour limit). Break task into smaller steps or optimize queries.
To prevent errors, design routines defensively: check if files exist before reading, use try-catch for API calls, log every step.
Quick reference
- Idempotency key: include a unique ID in commits/API calls to detect duplicate runs (in case of retry).
- Logging: verbose logging (timestamps, step names) helps debug when routines fail.
- Test routines: before deploying to production, run a routine manually to catch errors.
- Canary routine: run a test version of a new routine for 1 week before trusting it.
- Circuit breaker: if a routine fails >5 times in a row, auto-disable it and alert the owner.
Remember this
Routines retry automatically on transient failures; design tasks to be robust (check preconditions, handle errors); manually re-run if all retries fail.
Cost Per Routine and Budgeting
Routines are priced per execution. Example costs (as of Aug 2026):
- Daily routine (runs 30 times/month): ~$3–5/month (depending on task complexity).
- Weekly routine (runs 4 times/month): ~$0.50–1/month.
- Hourly routine (runs 720 times/month): ~$50–100/month (expensive; use sparingly).
Costs depend on: - Task complexity: A 5-minute security scan costs less than a 30-minute training run. - Model used: Claude 3.5 Sonnet (fast) vs Claude Opus (more expensive but smarter). - Output size: Large reports cost more than short summaries.
Cost optimization: 1. Reduce frequency: Daily might not be necessary; try 3x/week. 2. Batch tasks: Instead of 5 daily routines, combine into 1 routine that does all checks. 3. Pre-filter: Reduce data fed to Claude; filter logs before asking Claude to analyze. 4. Use cheaper models: For simple tasks (linting, formatting), use Claude 3.5 Sonnet.
Example budget: - Daily security scan: $5/month. - Weekly dependency audit: $1/month. - Morning briefing (5 days/week): $3/month. - Total: ~$10/month for 3 routines.
Scale up: If you have 50 routines, monthly cost could be $100–500. Monitor costs and disable unused routines.
Quick reference
- Cost per execution: Claude shows estimated cost before you create a routine.
- Billing: charges appear on your Claude Code billing statement.
- Budget alerts: set a monthly spending cap; Claude alerts if you're approaching it.
- Reserved compute: for high-volume routines, negotiate a fixed rate with Claude.
- Trial period: first 30 days of a routine are often discounted or free.
Remember this
Routines cost $0.10–1 per execution; daily routines ~$3/month; optimize by reducing frequency, batching tasks, and using cheaper models.
Real Examples: Security Scans and Briefings
Example 1: Daily Security Scan + Auto-Fix
1Routine: Daily SAST Scan2Schedule: 0 9 * * * (9 AM UTC)3Task: Run static analysis on src/ directory. Check for:4 - SQL injection in query builders5 - XSS in template rendering6 - Hardcoded passwords/API keys7 - Unvalidated user input8 9Output format:10 {11 "issues": [12 { "file": "src/api/users.ts", "line": 42, "severity": "HIGH", "issue": "SQL injection", "fix": "Use parameterized query" }13 ],14 "total_high": 2,15 "total_medium": 5,16 "total_low": 1217 }18 19Notification: Post to Slack #security with summary. If high-severity issues found, email security@company.com.20Auto-fix: If Claude can auto-fix (e.g., add input validation), create a PR. Otherwise, create a GitHub issue for manual review.Example 2: Morning Team Briefing
1Routine: Monday-Friday Morning Standup2Schedule: 0 7 * * MON-FRI (7 AM UTC weekdays)3Task: Gather and summarize:4 1. Open PRs awaiting review (older than 4 hours)5 2. Failed CI checks in the last 12 hours6 3. Open issues tagged "urgent" or "blocker"7 4. Recent commits with breaking changes8 9Format: A Slack message with 4 sections, each with a short summary and links.10 11Example output:12 📋 Morning Briefing (Monday, Aug 18)13 14 👀 PRs Awaiting Review: 315 • #1234 - Auth refactor (opened 16h ago) @alice16 • #1235 - Add caching (opened 12h ago) @bob17 18 ❌ Failed CI: 219 • #1236 - Test failure in payments (1h ago)20 • main branch - Lint error (30m ago)21 22 🚨 Urgent Issues: 123 • #5678 - Production bug: API timeout (opened 2h ago)24 25 ⚡ Breaking Changes: 126 • Commit abc123 - Removed deprecated /old-api endpoint27 28Post to Slack #standup at 7 AM UTC.Quick reference
- Real-time data: briefing includes data from last 12-24 hours; schedule at start of workday.
- Filtering: configure which issues/PRs appear (min age, labels, priority).
- Escalation: include @mentions for urgent items (e.g., @on-call for blocker issues).
- Summary link: include link to detailed dashboard so teams can drill down.
- Frequency: daily briefing (Mon-Fri) keeps team aligned without overhead.
Remember this
Real routines: daily security scans with auto-fixes, morning briefings with urgent summaries, dependency audits with notifications.
Routines vs Self-Hosted Cron Jobs
Why use Claude routines instead of cron on your own server?
| Feature | Claude Routines | Self-Hosted Cron | |---------|-----------------|-----------------| | Setup | 5 minutes in Claude console | 30 min + infrastructure | | Maintenance | Zero; Claude manages runners | Your responsibility (patching, backups) | | Scalability | Automatic; handles 1000s | Limited by your hardware | | Observability | Built-in dashboard + logs | Need to set up monitoring | | Cost | Pay per execution ($0.10–1) | Server cost (~$20–100/month) + your time | | Reliability | 99.9% uptime SLA | Depends on your infrastructure | | Secrets | Secure secret manager built-in | You manage SSH keys, env vars | | Retries | Automatic exponential backoff | You build retry logic |
When to use Claude routines: - Ad-hoc tasks (security scans, reports, audits). - Tasks that change frequently (prompts evolve). - Small to medium volume (<50 routines). - No dedicated infrastructure team.
When to use self-hosted cron: - High-volume, time-critical tasks (100+ jobs/minute). - Complex job dependencies (cron can't handle). - Cost-sensitive (cron overhead is minimal, Claude adds $). - Deep integration with internal infrastructure.
Most teams benefit from a hybrid: Claude routines for code-related tasks, cron for ops tasks.
Quick reference
- Hybrid approach: use Claude for code analysis/generation, cron for infra tasks (backups, monitoring).
- Migration path: start with Claude routines; if costs/features don't fit, migrate to cron.
- Vendor lock-in: Claude routines are Claude-specific; cron is portable (any Linux server).
- Warmup time: Claude routines have overhead (~2–5 sec per execution); not suitable for sub-second tasks.
- Comparison: run a pilot routine for 1 month; measure costs vs self-hosted cron before deciding.
Remember this
Claude routines: easy setup, zero maintenance, good for code tasks. Self-hosted cron: lower cost, full control, better for ops. Use both in a hybrid approach.
Key takeaway
Routines automate the tasks your team runs repeatedly. Instead of reminding people to audit dependencies every week, a routine does it at 6 AM Monday. Results land in Slack; if issues are found, a PR is auto-created. Your team reviews and approves. This pattern scales: 10 routines covering security, quality, and operations run silently in the background.
Practice: Create a simple routine that runs daily at 9 AM UTC and generates a 1-line message: "Good morning! Routine executed successfully." Expected result: at 9 AM the next day, you see the routine execution logged in the Claude console. Once working, update the routine to fetch the current day's weather for your timezone and include it in the message. Test manual re-runs from the dashboard to verify you can override the schedule.
Polo Khan
Lead Author & Systems ArchitectSoftware engineer and distributed systems architect specializing in backend scalability, cloud-native infrastructure, databases, and AI engineering workflows. Author and maintainer of Core Concept Learning.
Related Articles
Explore this topic