PTENES
4.4 ~40 min · Intermediate

⏰ Cron and recurring tasks

Schedule agents to run at set intervals — daily reviews, automatic reports, and continuous monitoring without human intervention.

👤 Manual you do everything 🤝 Assisted Claude Code helps ⏰ Scheduled cron fires 🚀 Autonomous 24/7 remote agent 0h saved 2h/week 8h/week 20h/week Automation ladder — each step multiplies the time freed up

⏰ Cron and scheduling

Cron is the standard Unix syntax for defining run times. Claude Code integrates with cron via the skill /schedule — you define the task in natural language and the system creates the scheduled routine.

The skill /schedule lets you create remote agents that run at defined intervals without needing an open local terminal.

// Cron syntax: minute hour day_of_month month day_of_week
0 9 * * 1-5    → 9h, segunda a sexta
0 9 * * 1       → 9h todo domingo
*/30 * * * *    → a cada 30 minutos
0 0 * * *       → meia-noite todo dia
0 8 1 * *       → 8h no dia 1 de cada mês

// Com a skill /schedule (linguagem natural):
/schedule todo dia útil às 9h: revisar commits do dia anterior
/schedule toda segunda às 8h: gerar relatório semanal de métricas
/schedule a cada hora: verificar se há PRs aguardando review

⏰ Use cron when

  • → Fixed, predictable schedule
  • → Terminal can be closed
  • → Task needs to run in production
  • → Multiple days/weeks in the future

🔁 Use /loop when

  • → Polling during an active session
  • → Short interval (every 5-30 min)
  • → Temporary monitoring
  • → You want to cancel manually

🔁 Loop and interval: the /loop command

O /loop repeats a slash command at set intervals while the session is active. Each iteration is an independent run — with no context carried over between rounds.

// Examples of using /loop
/loop 5m /status
→ Verifica o status do projeto a cada 5 minutos

/loop 30m Verifique se há novos erros no log de erros do servidor
→ Prompt livre com auto-pace (Claude decide quando repetir)

/loop 1h /code-review
→ Code review a cada hora (útil em sessões longas de desenvolvimento)

// Cancelar: Ctrl+C (encerra o loop)
// Ver status: /status (mostra próxima execução)

⚠️ Watch out for context pressure

O /loop accumulates context over the course of iterations. After many rounds, the context gets heavy and slow. Use /compact periodically or configure the loop to clear the context between iterations.

🌐 Remote agents

Remote agents run on Claude's infrastructure without needing an open local terminal. They're triggered by events (webhook, cron) and run completely autonomously — you only receive the result when they finish.

O RemoteTrigger is the tool that launches a remote agent. The PushNotification sends the result via webhook when the agent finishes.

💻 Local agent

  • → Requires an open terminal
  • → Pauses when you close the laptop
  • → Full access to the local filesystem
  • → Ideal for active development
  • → Cost: tokens used only

☁️ Remote agent

  • → Runs without an open terminal
  • → Continues even when the laptop is off
  • → Access via API and remote repository
  • → Ideal for production automation
  • → Cost: tokens + remote compute

📋 Example: automated daily review

The most popular use case: a code review agent that runs every day at 9 a.m., analyzes the previous day's commits, and generates a quality report.

1

Cron runs at 9 a.m.

Schedule created with /schedule: "every business day at 9 a.m., run the review workflow"

2

Agent collects commits

git log --since=yesterday --oneline + diff of each commit since the last tag

3

Quality analysis

Checks: business logic, edge cases, security, performance, missing tests

4

Report saved + notification

Saves to .reviews/YYYY-MM-DD.md + sends via webhook to Slack/Discord

// Prompt to create the schedule via /schedule
/schedule todo dia útil às 9h: 
  1. Execute: git log --since=yesterday --name-only --oneline
  2. Para cada arquivo modificado, execute /code-review
  3. Consolide os achados em .reviews/$(date +%Y-%m-%d).md
     Formato: ## Data · N commits · Qualidade: Alta/Média/Baixa
     Seções: Pontos Positivos, Riscos, Ações Recomendadas
  4. Se houver riscos ALTOS, poste no webhook $SLACK_WEBHOOK_URL

// O agente usa prompt caching para o contexto base
// (CLAUDE.md + CHECKLIST.md) — 90% mais barato por rodada

📥 Capture the result from asynchronous agents

Asynchronous agents (cron, remote) don't return results immediately. You need to define where the output will be delivered before launching the agent.

📁 File

The agent saves the report to a configurable path. Simple, with no external dependencies.

.reviews/2026-06-01.md

🔔 Webhook

PushNotification sends the result to Slack, Discord, n8n, or any HTTP endpoint.

POST $WEBHOOK_URL

👁️ Monitor

Real-time event stream. Use when you want to monitor execution.

/monitor task-id

💡 Automation without observability = blind automation

Always configure at least one output mechanism before before activating a recurring agent. An agent that fails silently for weeks is worse than having no automation — it creates a false sense of security.

⚠️ Cost and idempotency in production

Recurring agents accumulate costs over time. A daily review that costs $0.10/day = $30/month = $365/year. It seems cheap, but if a bug makes the agent run twice, the cost doubles. Idempotency solves this.

Idempotency: running the agent N times produces the same result as running it once. Crucial when failures trigger automatic reruns.

✓ Production practices

  • ✓ Check before acting: verify whether the task has already been done today
  • ✓ Lock file: prevent simultaneous runs of the same agent
  • ✓ Budget alerts: notify when cost exceeds the threshold
  • ✓ Enable prompt caching for fixed context (CLAUDE.md)

✗ Production pitfalls

  • ✗ Agent that creates identical PRs if it runs 2× on the same day
  • ✗ No cost alerts — surprises on the monthly bill
  • ✗ Agent with write access to the production database
  • ✗ No output configured — you don't know if it worked
// Idempotent pattern: check before acting
#!/bin/bash # .claude/hooks/idempotency-check.sh
DATE=$(date +%Y-%m-%d)
LOCK_FILE=".reviews/.lock-$DATE"

# Se o arquivo de lock existir, o review já rodou hoje
if [ -f "$LOCK_FILE" ]; then
  echo "Review de $DATE já executado. Pulando." >&2
  exit 0
fi

# Cria o lock antes de começar
touch "$LOCK_FILE"

# ... resto da execução ...

# Se falhar, remove o lock para permitir retry
trap "rm -f '$LOCK_FILE'" ERR

🎯 Module 4.4 Summary

✓
Cron + /schedule — scheduling tasks at fixed times using cron syntax or natural language
✓
/loop — polling at intervals during an active session, cancellable with Ctrl+C
✓
Remote agents — run without a local terminal, triggered by RemoteTrigger
✓
Daily review — complete pattern: cron → collect commits → analysis → report → webhook
✓
Idempotency — lock file + check-before-acting prevents duplicate executions

🏆 Track 4 complete!

You mastered the 4 pillars of automation in Claude Code: subagents to parallelize, hooks for automatic policies, slash commands for consistency, and cron so it never sleeps.

Next step: apply all this to real projects in Track 5 — Projects.

🏗️ Next Track:

Track 5 — Projects: apply subagents, hooks, and workflows in real projects from start to finish