> 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.1-cron-system-design.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 26.1 Cron System Design

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~200k tokens, Output \~6k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

AI Agents should not only work when users actively engage in conversation. OpenClaw's Cron system enables Agents to **automatically execute tasks on a schedule**—sending daily news summaries, checking email every hour, or reminding users at specific times. This section analyzes the core design of the Cron system: the service class, scheduling engine, expression parsing, and job normalization.

***

## 26.1.1 Cron Service (`src/cron/service.ts`)

### Class Design

`CronService` is the Facade for the Cron system, encapsulating all scheduled task management operations:

```typescript
// src/cron/service.ts

export class CronService {
  private readonly state;

  constructor(deps: CronServiceDeps) {
    this.state = createCronServiceState(deps);
  }

  async start()  { await ops.start(this.state); }
  stop()         { ops.stop(this.state); }

  async status() { return await ops.status(this.state); }
  async list(opts?: { includeDisabled?: boolean }) { ... }
  async add(input: CronJobCreate)  { return await ops.add(this.state, input); }
  async update(id: string, patch: CronJobPatch) { ... }
  async remove(id: string) { ... }
  async run(id: string, mode?: "due" | "force") { ... }

  wake(opts: { mode: "now" | "next-heartbeat"; text: string }) {
    return ops.wakeNow(this.state, opts);
  }
}
```

All actual logic is delegated to pure functions in `service/ops.ts`, with `CronService` itself serving as a thin wrapper. This design facilitates testing—you can test `ops` functions directly without instantiating the entire service.

### Dependency Injection

`CronServiceDeps` defines all external dependencies required by the Cron service:

```typescript
// src/cron/service/state.ts

export type CronServiceDeps = {
  nowMs?: () => number;              // Time source (injectable fake clock)
  log: Logger;                       // Logging interface
  storePath: string;                 // Job storage file path
  cronEnabled: boolean;              // Whether scheduling is enabled
  enqueueSystemEvent: (text: string, opts?) => void;  // Send system event
  requestHeartbeatNow: (opts?) => void;              // Request immediate heartbeat
  runHeartbeatOnce?: (opts?) => Promise<HeartbeatRunResult>;  // Sync heartbeat
  runIsolatedAgentJob: (params) => Promise<{...}>;   // Run isolated Agent
  onEvent?: (evt: CronEvent) => void;                // Event callback
};
```

| Dependency            | Description                                                                  |
| --------------------- | ---------------------------------------------------------------------------- |
| `nowMs`               | Injectable time source; use fake clock in tests for precise timing control   |
| `enqueueSystemEvent`  | Push text to the main session's system event queue (e.g., reminder messages) |
| `requestHeartbeatNow` | Request Agent to immediately process queued events                           |
| `runIsolatedAgentJob` | Run Agent in an isolated session (for standalone Cron tasks)                 |
| `onEvent`             | Event callback; Gateway uses it to broadcast Cron events to clients          |

### Internal State

```typescript
export type CronServiceState = {
  deps: CronServiceDepsInternal;
  store: CronStoreFile | null;     // In-memory job list (loaded from file)
  timer: NodeJS.Timeout | null;    // Current setTimeout handle
  running: boolean;                // Whether a job is executing (prevents re-entry)
  op: Promise<unknown>;            // Operation serialization lock
  warnedDisabled: boolean;          // Whether disabled state warning was issued
  storeLoadedAtMs: number | null;  // Last time store was loaded
  storeFileMtimeMs: number | null; // File modification time at last load
};
```

The `store` field is critical—all job data is persisted as a JSON file on disk (default `~/.openclaw/cron/jobs.json`), loaded into memory at startup, and written back to disk after modifications. This is a simple "file-as-database" persistence approach suitable for single-user scenarios.

### Startup Flow

```typescript
// src/cron/service/ops.ts — start

export async function start(state: CronServiceState) {
  await locked(state, async () => {
    if (!state.deps.cronEnabled) {
      state.deps.log.info({ enabled: false }, "cron: disabled");
      return;
    }

    // 1. Load job store
    await ensureLoaded(state, { skipRecompute: true });

    // 2. Clear stale "running" markers (process may have crashed last time)
    for (const job of state.store?.jobs ?? []) {
      if (typeof job.state.runningAtMs === "number") {
        state.deps.log.warn({ jobId: job.id }, "cron: clearing stale running marker");
        job.state.runningAtMs = undefined;
      }
    }

    // 3. Execute missed jobs (tasks that expired during process restart)
    await runMissedJobs(state);

    // 4. Recompute next run times for all jobs
    recomputeNextRuns(state);

    // 5. Persist state
    await persist(state);

    // 6. Set timer
    armTimer(state);
  });
}
```

The startup flow includes two important recovery mechanisms:

* **Clear stale markers**—if the process crashes during job execution, the `runningAtMs` marker persists and must be cleared at startup
* **Catch up on missed jobs**—`runMissedJobs` finds all enabled jobs whose `nextRunAtMs` has passed and executes them immediately

### Operation Serialization

All operations are serialized through the `locked()` function, preventing concurrent modifications that could cause data races:

```typescript
// src/cron/service/locked.ts — locked (conceptual implementation)

export async function locked<T>(state: CronServiceState, fn: () => Promise<T>): Promise<T> {
  // Queue the operation, ensuring the previous one completes first
  const prev = state.op;
  const next = prev.then(() => fn());
  state.op = next.catch(() => {});
  return await next;
}
```

> **Sidebar—Operation Serialization**: In single-threaded Node.js, while there's no true thread concurrency, async/await can cause interleaved execution. For example, two concurrent `add()` calls might simultaneously read the store, modify it, and write it back, causing one operation's changes to be overwritten. `locked()` ensures operations execute sequentially via Promise chaining, acting like an async mutex.

***

## 26.1.2 Scheduling Engine (`src/cron/schedule.ts`) and Croner Library

### Three Scheduling Types

OpenClaw supports three scheduling methods:

```typescript
// src/cron/types.ts

export type CronSchedule =
  | { kind: "at"; at: string }                              // One-time: execute at specified time
  | { kind: "every"; everyMs: number; anchorMs?: number }   // Periodic: fixed interval
  | { kind: "cron"; expr: string; tz?: string };            // Cron expression
```

| Type    | Example                           | Purpose                             |
| ------- | --------------------------------- | ----------------------------------- |
| `at`    | `"2026-03-01T09:00:00Z"`          | One-time reminders, scheduled tasks |
| `every` | `everyMs: 3600000` (1 hour)       | Fixed-interval polling              |
| `cron`  | `"0 9 * * 1-5"` (weekdays at 9am) | Standard Cron expressions           |

### `computeNextRunAtMs`: Computing Next Run Time

```typescript
// src/cron/schedule.ts — computeNextRunAtMs

export function computeNextRunAtMs(
  schedule: CronSchedule, nowMs: number
): number | undefined {

  // One-time scheduling
  if (schedule.kind === "at") {
    const atMs = parseAbsoluteTimeMs(schedule.at);
    return atMs !== null && atMs > nowMs ? atMs : undefined;
  }

  // Fixed-interval scheduling
  if (schedule.kind === "every") {
    const everyMs = Math.max(1, Math.floor(schedule.everyMs));
    const anchor = Math.max(0, Math.floor(schedule.anchorMs ?? nowMs));
    if (nowMs < anchor) return anchor;
    const elapsed = nowMs - anchor;
    const steps = Math.max(1, Math.floor((elapsed + everyMs - 1) / everyMs));
    return anchor + steps * everyMs;
  }

  // Cron expression scheduling
  const cron = new Cron(expr, {
    timezone: resolveCronTimezone(schedule.tz),
    catch: false,
  });
  let cursor = nowMs;
  for (let attempt = 0; attempt < 3; attempt++) {
    const next = cron.nextRun(new Date(cursor));
    if (!next) return undefined;
    const nextMs = next.getTime();
    if (Number.isFinite(nextMs) && nextMs > nowMs) return nextMs;
    cursor += 1_000;  // Avoid getting stuck at boundary
  }
  return undefined;
}
```

**Anchor mechanism for `every` type**: `anchorMs` is the reference starting point for the interval. The next run time is computed as `anchor + N × everyMs` (taking the smallest N greater than `nowMs`). This ensures that even if the process restarts, the interval is calculated from the original anchor point, not from the restart time.

> **Sidebar—Croner**: Croner is a lightweight Cron expression parsing library (pure JavaScript, no dependencies). It supports standard 5-field Cron expressions (minute hour day month weekday) and provides a `nextRun()` method to compute the next matching time. OpenClaw uses it to parse Cron expressions but not its job scheduling functionality—scheduling logic is implemented by OpenClaw's own `armTimer`.

### Timezone Handling

```typescript
function resolveCronTimezone(tz?: string) {
  const trimmed = typeof tz === "string" ? tz.trim() : "";
  if (trimmed) return trimmed;  // User-specified timezone
  return Intl.DateTimeFormat().resolvedOptions().timeZone;  // System default
}
```

Cron expressions default to the system timezone, but users can specify an IANA timezone identifier via the `tz` field (e.g., `"America/New_York"`, `"Asia/Shanghai"`).

### Timer Mechanism

`armTimer` sets up the next `setTimeout` wake-up:

```typescript
// src/cron/service/timer.ts — armTimer

const MAX_TIMER_DELAY_MS = 60_000;  // Maximum delay: 1 minute

export function armTimer(state: CronServiceState) {
  if (state.timer) clearTimeout(state.timer);
  state.timer = null;

  if (!state.deps.cronEnabled) return;

  const nextAt = nextWakeAtMs(state);  // Nearest next run time among all jobs
  if (!nextAt) return;

  const delay = Math.max(nextAt - state.deps.nowMs(), 0);
  // Key: cap maximum delay at 1 minute
  const clampedDelay = Math.min(delay, MAX_TIMER_DELAY_MS);

  state.timer = setTimeout(async () => {
    await onTimer(state);
  }, clampedDelay);
}
```

**Why cap at 1 minute maximum delay?** The comment explains: "Avoid scheduling drift and quickly recover when the process is suspended or system clock jumps." JavaScript's `setTimeout` can drift significantly after system sleep (e.g., laptop lid closed). Waking up every minute allows detection of such conditions and timely execution of expired jobs.

***

## 26.1.3 Cron Expression Parsing (`src/cron/parse.ts`)

`parse.ts` is responsible for parsing various time formats into Unix millisecond timestamps:

```typescript
// src/cron/parse.ts — parseAbsoluteTimeMs

const ISO_TZ_RE = /(Z|[+-]\d{2}:?\d{2})$/i;
const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
const ISO_DATE_TIME_RE = /^\d{4}-\d{2}-\d{2}T/;

function normalizeUtcIso(raw: string) {
  if (ISO_TZ_RE.test(raw))        return raw;              // Already has timezone: return as-is
  if (ISO_DATE_RE.test(raw))      return `${raw}T00:00:00Z`;  // Pure date → 00:00 UTC that day
  if (ISO_DATE_TIME_RE.test(raw)) return `${raw}Z`;           // No timezone → UTC
  return raw;
}

export function parseAbsoluteTimeMs(input: string): number | null {
  const raw = input.trim();
  if (!raw) return null;

  // Pure digits → treat as Unix millisecond timestamp
  if (/^\d+$/.test(raw)) {
    const n = Number(raw);
    return Number.isFinite(n) && n > 0 ? Math.floor(n) : null;
  }

  // Try parsing as ISO date/datetime
  const parsed = Date.parse(normalizeUtcIso(raw));
  return Number.isFinite(parsed) ? parsed : null;
}
```

Supported time formats:

| Input Format                 | Example                       | Parsing Method                         |
| ---------------------------- | ----------------------------- | -------------------------------------- |
| Unix milliseconds            | `"1709280000000"`             | Direct conversion to number            |
| ISO date                     | `"2026-03-01"`                | Expand to `2026-03-01T00:00:00Z`       |
| ISO datetime (no timezone)   | `"2026-03-01T09:00:00"`       | Expand to UTC (`2026-03-01T09:00:00Z`) |
| ISO datetime (with timezone) | `"2026-03-01T09:00:00+08:00"` | Parse as-is                            |

***

## 26.1.4 Cron Normalization (`src/cron/normalize.ts`)

### Problem: LLM Input is Unreliable

Cron jobs are typically created by Agents via tool calls. LLM-generated parameters may:

* Have inconsistent casing (`"SystemEvent"` vs `"systemEvent"`)
* Use legacy field names (`atMs` vs `at`, `deliver` vs `delivery`)
* Lack required default values
* Have fields in wrong places (`model` at top level instead of inside `payload`)

`normalize.ts` is responsible for normalizing these "dirty inputs" into a unified internal format.

### Three-Layer Normalization

```typescript
// src/cron/normalize.ts — core structure

export function normalizeCronJobInput(raw: unknown, options): UnknownRecord | null {
  const base = unwrapJob(raw);        // 1. Unwrap nesting (data/job wrapper)
  const next = { ...base };

  // 2. Normalize individual fields
  if (isRecord(base.schedule))  next.schedule = coerceSchedule(base.schedule);
  if (isRecord(base.payload))   next.payload = coercePayload(base.payload);
  if (isRecord(base.delivery))  next.delivery = coerceDelivery(base.delivery);

  // 3. Backward compatibility: migrate top-level fields to payload
  copyTopLevelAgentTurnFields(next, payload);
  copyTopLevelLegacyDeliveryFields(next, payload);
  stripLegacyTopLevelFields(next);

  // 4. Apply defaults (only for create, not for patch)
  if (options.applyDefaults) {
    if (!next.wakeMode) next.wakeMode = "now";
    if (typeof next.enabled !== "boolean") next.enabled = true;
    // ... more defaults
  }

  return next;
}
```

### Schedule Normalization

```typescript
function coerceSchedule(schedule: UnknownRecord) {
  const next = { ...schedule };
  const rawKind = schedule.kind?.trim().toLowerCase();
  const kind = rawKind === "at" || rawKind === "every" || rawKind === "cron"
    ? rawKind : undefined;

  // Auto-infer kind
  if (!kind) {
    if (schedule.atMs || schedule.at)        next.kind = "at";
    else if (typeof schedule.everyMs === "number") next.kind = "every";
    else if (typeof schedule.expr === "string")    next.kind = "cron";
  }

  // atMs (legacy numeric format) → at (new ISO string format)
  if ("atMs" in next) {
    next.at = new Date(parsedAtMs).toISOString();
    delete next.atMs;
  }

  return next;
}
```

### Payload Normalization

```typescript
function coercePayload(payload: UnknownRecord) {
  const next = { ...payload };

  // Fix casing: agentturn → agentTurn, systemevent → systemEvent
  if (kindRaw === "agentturn")     next.kind = "agentTurn";
  if (kindRaw === "systemevent")   next.kind = "systemEvent";

  // Auto-infer payload type
  if (!next.kind) {
    if (next.message) next.kind = "agentTurn";
    else if (next.text) next.kind = "systemEvent";
  }

  // Clean up empty string fields
  if (typeof next.model === "string" && !next.model.trim()) delete next.model;
  if (typeof next.thinking === "string" && !next.thinking.trim()) delete next.thinking;

  return next;
}
```

### Delivery Configuration Normalization

```typescript
function coerceDelivery(delivery: UnknownRecord) {
  const next = { ...delivery };

  // Rename "deliver" mode to "announce"
  if (mode === "deliver") next.mode = "announce";

  // Trim and lowercase channel and to fields
  if (typeof delivery.channel === "string") {
    next.channel = delivery.channel.trim().toLowerCase();
  }

  return next;
}
```

### Default Value Strategy

The difference between `normalizeCronJobCreate` and `normalizeCronJobPatch` is whether defaults are applied:

```typescript
// Create: apply defaults
export function normalizeCronJobCreate(raw) {
  return normalizeCronJobInput(raw, { applyDefaults: true });
}

// Patch: don't apply defaults (only modify explicitly specified fields)
export function normalizeCronJobPatch(raw) {
  return normalizeCronJobInput(raw, { applyDefaults: false });
}
```

Key defaults:

| Field            | Default Value                                     | Condition                                                   |
| ---------------- | ------------------------------------------------- | ----------------------------------------------------------- |
| `wakeMode`       | `"now"`                                           | Always                                                      |
| `enabled`        | `true`                                            | Always                                                      |
| `sessionTarget`  | `"main"` (systemEvent) / `"isolated"` (agentTurn) | Inferred from payload type                                  |
| `deleteAfterRun` | `true`                                            | Only for `at` type (one-time tasks deleted after execution) |
| `delivery.mode`  | `"announce"`                                      | Only for isolated agentTurn tasks                           |

***

## Section Summary

1. `CronService` is the Facade for the Cron system; all logic is delegated to pure functions in the `ops` module
2. **Dependency injection** enables testability—time source, logging, and Agent executor are all injectable
3. All operations are serialized via **Promise chaining**, avoiding async concurrency-induced data races
4. Three scheduling types supported: **one-time** (`at`), **fixed interval** (`every`), **Cron expression** (`cron`)
5. Scheduling engine uses **Croner library** to parse Cron expressions; timer caps maximum delay at **1 minute** to handle system sleep
6. Time parsing supports **Unix milliseconds, ISO dates, ISO datetimes**; missing timezone defaults to UTC
7. Normalization module handles unreliable LLM-generated input—case correction, legacy field migration, type auto-inference, default filling
8. `create` and `patch` operations use different normalization strategies—create applies defaults, patch only modifies explicit fields
