> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch26-cron-scheduling-and-automation/26.4-source-deep-dive-cron-vs-heartbeat.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 26.4 Source Deep Dive: The Division of Labor Between cron and heartbeat

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~246,000 tokens, Output \~13,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`); line numbers refer to this commit

***

A resident agent needs to be able to wake up. OpenClaw has two wake mechanisms with a very clear division:

* **cron** handles **punctuality** (precise scheduling plus isolation);
* **heartbeat** handles **awareness** (batched, riding along to save tokens).

This section reads both, along with the defenses each was beaten into shape by real incidents.

## 26.4.1 One Scheduler, Two Session Shapes

The cron subsystem (`src/cron/`, 8,972 lines, **about half of which are regression tests for historical issues**) supports three schedule kinds (`src/cron/types.ts:5-14`):

| Kind            | Meaning                                               |
| --------------- | ----------------------------------------------------- |
| `at`            | One-shot                                              |
| `every`         | Fixed interval                                        |
| cron expression | Standard five-field, with timezone and stagger window |

Jobs come in two binding shapes, **with pairing enforced at creation time**:

```ts
// src/cron/service/jobs.ts:134-141
export function assertSupportedJobSpec(job: Pick<CronJob, "sessionTarget" | "payload">) {
  if (job.sessionTarget === "main" && job.payload.kind !== "systemEvent") {
    throw new Error('main cron jobs require payload.kind="systemEvent"');
  }
  if (job.sessionTarget === "isolated" && job.payload.kind !== "agentTurn") {
    throw new Error('isolated cron jobs require payload.kind="agentTurn"');
  }
}
```

**Enforcing pairing at the type level keeps misuse out at creation time** — rather than discovering at runtime that "a main session somehow started an independent agent turn."

### Shape one: main + systemEvent

**No separate agent turn.** It only pushes a system event onto the main session's event queue (`src/cron/service/timer.ts:1057`).

* `wakeMode: "now"` → pull up a heartbeat immediately;
* Otherwise → handled incidentally on the next heartbeat cycle.

Good for "remind me in 20 minutes" — **lightweight tasks that need main-session context**. The cost is essentially zero because it rides along with the heartbeat.

### Shape two: isolated + agentTurn

Starts a **clean** agent turn under the session key `cron:<jobId>` (`src/cron/isolated-agent/run.ts`, 879 lines).

* Model / thinking / timeout can be overridden per job (**run scheduled work on a cheaper model**);
* On completion, results are delivered per the delivery plan: `announce` (send a summary through a message channel) / `webhook` (HTTP POST) / `none`.

Each run's temporary session `...:cron:<jobId>:run:<uuid>` is reclaimed by the session reaper after **24 hours** (`src/cron/session-reaper.ts:5-8`'s comment is explicit: "base session preserved, run records reclaimed").

### The full sequence

```mermaid
sequenceDiagram
  participant T as CronService timer
  participant M as Main session
  participant I as Isolated session cron:jobId
  participant C as Message channel
  Note over T: armTimer sets one setTimeout for the nearest nextRunAtMs
  alt sessionTarget = main
    T->>M: enqueueSystemEvent(text)
    opt wakeMode = now
      T->>M: requestHeartbeatNow()
    end
    M->>C: the heartbeat turn handles the event and replies if needed
  else sessionTarget = isolated
    T->>I: runCronAgentTurn(payload.message, model override)
    I-->>T: outputText + run telemetry
    alt delivery = announce/webhook
      T->>C: send summary / HTTP POST
    else delivery failed and fallback allowed
      T->>M: forward summary to the main session (shouldEnqueueCronMainSummary)
    end
  end
```

## 26.4.2 The Scheduler's Defensive Engineering

The whole scheduler uses **exactly one `setTimeout`**: `armTimer` computes the nearest `nextRunAtMs` across all jobs and arms a single timer (`src/cron/service/timer.ts:507-540`), re-arming after any job change.

That unremarkable-looking function contains several incident lessons.

### Incident one: the `setTimeout(0)` hot loop

```ts
// src/cron/service/timer.ts:534-541 (excerpt)
const delay = Math.max(nextAt - now, 0);
// Floor: when the next wake time is in the past (delay === 0), enforce a
// minimum delay to prevent a tight setTimeout(0) loop.  This can happen
// when a job has a stuck runningAtMs marker and a past-due nextRunAtMs:
```

**Trigger conditions**: a job with a stuck `runningAtMs` marker (so it never executes) plus a past-due `nextRunAtMs` (so the computed delay is 0).

The result is an infinite `setTimeout(0)` hot loop pinning a CPU.

The fix is to **enforce a minimum delay**. The corresponding regression test is literally named `service.armtimer-tight-loop.test.ts`.

### Incident two: the post-restart catch-up storm

Should missed jobs run after a gateway restart?

Two rules:

1. **Only jobs with run history replay missed slots** (`timer.ts:798`) — a job created but never run doesn't catch up;
2. **Backlogged jobs are re-staggered** (`timer.ts:891`'s log reads: "staggering missed jobs to prevent gateway overload").

The second defends against: restart after a three-day power outage, dozens of daily jobs all due at once, instantly overwhelming the gateway and the model API.

### Incident three: stuck runs

`STUCK_RUN_MS = 2 hours` (`jobs.ts:35`). A job still marked running beyond that is considered dead.

### Two elegant scheduling details

**Deterministic staggering.**

On-the-hour cron jobs are staggered by default within a 0–5 minute window using the **SHA-256 digest of the job id**:

```ts
// jobs.ts:52-53 semantics
digest.readUInt32BE(0) % staggerMs
```

This avoids everyone's "daily briefing" hitting the gateway and model API in the same second (the thundering-herd effect).

**Using a hash of the job id rather than a random number** means a given job's offset is **permanently stable** — the execution time a user sees doesn't jump around day to day.

**Failure backoff and auto-disable.**

* Consecutive failures of an isolated job accumulate backoff and trigger a **failure alert on a separate channel** (with a cooldown);
* **Persistent errors in schedule computation itself auto-disable the job.**

The second defends against "the config is broken and nobody reads the logs" — a malformed cron expression is better disabled with an alert than erroring once a minute for three months.

> There are a dozen-plus regression tests named after issue numbers under `src/cron/` (`service.issue-*.test.ts`). **A scheduler's correctness comes mainly from incident sediment, not from design.** That's this section's most important lesson: if you're writing a scheduler, expect to discover a new edge case every month, and turn every one into a regression test.

## 26.4.3 heartbeat: Batched Periodic Checks

heartbeat **doesn't live in `src/cron/`** — it's a periodic idle turn on the main session (30-minute interval by default).

How it works: read the workspace's `HEARTBEAT.md` checklist and **batch-check** mail, calendar, and background tasks **within one turn**; if nothing's up, reply `HEARTBEAT_OK`.

### It fully reuses the inbound pipeline

The implementation **doesn't build a second path**: `runHeartbeatOnce` (`src/infra/heartbeat-runner.ts:608-809`) hand-constructs a `MsgContext` with `Provider` set to `"heartbeat"` and then calls `getReplyFromConfig` as usual (the §14.5 pipeline).

That's good reuse — the heartbeat takes exactly the same path as a real user message, so there's no "the user path got fixed but the heartbeat path didn't" divergence.

### A set of yielding and silencing mechanisms

The scheduler (`startHeartbeatRunner`, `heartbeat-runner.ts:1010-1245`) maintains `nextDueMs` per agent, with the wake layer coalescing wakeups by reason.

What's genuinely interesting is its **restraint**:

**Yielding (never competing with the foreground)**

If the main lane has queued work it skips (`:639-642`), **and does not advance the scheduled time**, relying on the wake layer to retry a second later (`:1200-1206`).

The comment explains why it can't just call `scheduleNext`: **a 0 ms timer would race the retry and win, bypassing the cooldown.**

And if by the time the heartbeat reaches the agent layer the session happens to have an active run, `resolveActiveRunQueueAction` returns `drop` (§13.6.2) — **a heartbeat never queues, never steers, and expires if it can't run.**

The design stance is explicit: **a heartbeat is "take a look when there's time," not "a task that must execute."** Anything that must execute belongs in cron.

**Saving money**

When `HEARTBEAT.md` is "effectively empty" (only headings and unchecked boxes) it **skips the API call entirely** (`src/auto-reply/heartbeat.ts:23-53`).

A user with no to-dos configured pays nothing for heartbeats at all.

**Silencing (the traceless design)**

This is the mechanism from §44.5.4. The conditions: the model replies `HEARTBEAT_OK` (**tolerating markup wrappers like `**HEARTBEAT_OK**` and `<b>HEARTBEAT_OK</b>`**, `heartbeat.ts:135-146`) and remaining text is ≤ 300 characters.

When satisfied, three things happen:

1. Don't disturb the user (send nothing);
2. **Roll back the session's `updatedAt`**;
3. **Trim that heartbeat turn out of the transcript** (`heartbeat-runner.ts:787-808`).

> That "tolerate markup wrappers" detail is very practical: models routinely bold keywords on their own initiative. A strict match on `HEARTBEAT_OK` misses `**HEARTBEAT_OK**`, turning a heartbeat that should have been silent into a nuisance message. **When you agree on a marker token with a model, always tolerate formatting.**

One more policy (`src/cron/heartbeat-policy.ts:9-29`'s `shouldSkipHeartbeatOnlyDelivery`): **suppression isn't allowed when there are media attachments** — if the model generated an image, there's something the user should see.

**Model degradation**

Heartbeats can use a separate cheaper model (`heartbeat.model`), applied preferentially at `get-reply.ts:86-103`.

## 26.4.4 The Division Criteria

The guidance in `docs/automation/cron-vs-heartbeat.md` compresses into one table:

| Dimension        | heartbeat                      | cron(main)                      | cron(isolated)                                 |
| ---------------- | ------------------------------ | ------------------------------- | ---------------------------------------------- |
| Session          | Main session                   | Main session (via system event) | Fresh `cron:<jobId>`                           |
| Context          | Complete                       | Complete                        | Clean                                          |
| Timing precision | **Drift acceptable**           | Precise                         | Precise                                        |
| Cost             | One turn amortizes many checks | **Nearly free** (rides along)   | A full turn each time; can use a cheaper model |

The selection logic:

```
Need main-session context?
  ├─ yes + timing-insensitive → heartbeat (put the checks in HEARTBEAT.md)
  ├─ yes + timing-sensitive   → cron(main) + systemEvent
  └─ no                       → cron(isolated) + agentTurn (cheaper model, restricted skills)
```

**Fallback path**: if an isolated cron job fails to deliver, there's a route that forwards the summary back to the main session, gated strictly by `shouldEnqueueCronMainSummary` (`heartbeat-policy.ts:31-48`) to avoid duplicate interruptions.

## 26.4.5 Automation Entry Points Are Wired to the Security Module

Isolated cron sessions are treated as a **potential external-content entry point**.

`run.ts` brings in `buildSafeExternalPrompt` / `detectSuspiciousPatterns` (`src/security/external-content.js`) to detect and wrap prompt injection for **externally triggered hook sessions like the Gmail watcher**.

The reasoning is direct: an email from a stranger triggers an agent turn, and the email body is untrusted input.

> Note this doesn't contradict §44.4's position: OpenClaw states clearly that prompt injection isn't a promised boundary, but **it still does the mitigation that should be done**. §45.3's point that "sanitization is defense in depth, not a boundary" — this is that in practice.

### Echoing the memory system

Cron sessions are excluded from `MEMORY.md` / `HEARTBEAT.md` by `filterBootstrapFilesForSession` (§28.5.2).

The `agentTurn` payload can additionally set `lightContext: true` (`src/cron/types.ts:94-95`), at which point **the bootstrap context is empty outright** (`src/agents/bootstrap-files.ts:58-60`'s comment: "cron/default lightweight mode keeps bootstrap context empty on purpose").

**High-frequency scheduled jobs get their token cost pushed to the floor** — a check running every five minutes doesn't need to know your boss's name.

Isolated cron sessions also get an independent skills snapshot filter (`src/cron/isolated-agent/skills-snapshot.ts`): scheduled jobs can run with only an allowlisted set of skills, **shrinking the automation turn's attack surface**.

***

## Section Summary

1. **Two session shapes with pairing enforced at creation**: `main + systemEvent` (rides the heartbeat, nearly free) and `isolated + agentTurn` (clean session, can use a cheaper model) — keeping misuse out at the type level.
2. **The entire scheduler uses one `setTimeout`**; three incident lessons live in the code: enforce a minimum delay when `delay === 0` (hot-loop prevention), only replay missed slots for jobs with run history and re-stagger them, and `STUCK_RUN_MS = 2h`.
3. **Deterministic staggering uses the job id's SHA-256 rather than a random number** — avoiding thundering herd while keeping each job's offset permanently stable.
4. **Persistent schedule errors auto-disable the job** — defending against "the config is broken and nobody reads the logs."
5. **About half of `src/cron/` is regression tests, a dozen-plus named after issue numbers** — a scheduler's correctness comes mainly from incident sediment, not design.
6. **heartbeat fully reuses the inbound pipeline** (hand-constructing a `MsgContext`), avoiding path divergence; **a heartbeat never queues, never steers, and expires if it can't run** — it's "take a look when there's time," not "must execute."
7. **The silencing trio**: send nothing + roll back `updatedAt` + trim the transcript; marker matching **tolerates markup wrappers** (models love to bold things); **suppression is disallowed when media attachments exist**.
8. **Automation entry points are wired to the security module**: externally triggered sessions get injection detection and wrapping; cron sessions receive the minimal bootstrap set, can set `lightContext: true` for an empty context, and can use an allowlisted skills snapshot to shrink the attack surface.
