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

# 26.2 Cron Job Execution

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

***

The previous section introduced the scheduling design of the Cron system. This section dives into actual job execution: how to distinguish between main-session jobs and isolated jobs, how delivery plans determine message destinations, how run logs are recorded, and the persistence mechanism of job storage.

***

## 26.2.1 Isolated Agent Execution (`src/cron/isolated-agent.ts`)

### Two Execution Modes

Cron jobs have two execution modes, determined by the `sessionTarget` field:

| Mode                 | `sessionTarget` | Payload Type  | How It Works                                                  |
| -------------------- | --------------- | ------------- | ------------------------------------------------------------- |
| **Main Session**     | `"main"`        | `systemEvent` | Inject system event text into main session, trigger heartbeat |
| **Isolated Session** | `"isolated"`    | `agentTurn`   | Start independent Agent session to execute task               |

```typescript
// src/cron/service/timer.ts — executeJobCore (simplified)

async function executeJobCore(state, job) {
  // Mode 1: Main session execution
  if (job.sessionTarget === "main") {
    const text = resolveJobPayloadTextForMain(job);
    if (!text) return { status: "skipped", error: "requires non-empty text" };

    // Inject system event
    state.deps.enqueueSystemEvent(text, { agentId: job.agentId });

    // Wake Agent to process
    if (job.wakeMode === "now" && state.deps.runHeartbeatOnce) {
      // Sync mode: wait for heartbeat to complete (max 2 minutes)
      for (;;) {
        const result = await state.deps.runHeartbeatOnce({ reason: `cron:${job.id}` });
        if (result.status !== "skipped" || result.reason !== "requests-in-flight") break;
        if (state.deps.nowMs() - waitStartedAt > 2 * 60_000) {
          state.deps.requestHeartbeatNow({ reason: `cron:${job.id}` });
          return { status: "ok", summary: text };
        }
        await delay(250);
      }
    } else {
      // Async mode: only request heartbeat, don't wait
      state.deps.requestHeartbeatNow({ reason: `cron:${job.id}` });
    }
    return { status: "ok", summary: text };
  }

  // Mode 2: Isolated session execution
  if (job.payload.kind !== "agentTurn") {
    return { status: "skipped", error: "isolated job requires agentTurn" };
  }
  const res = await state.deps.runIsolatedAgentJob({
    job,
    message: job.payload.message,
  });

  // Pass summary back to main session (if delivery is configured)
  const deliveryPlan = resolveCronDeliveryPlan(job);
  if (res.summary?.trim() && deliveryPlan.requested) {
    state.deps.enqueueSystemEvent(`Cron: ${res.summary}`, { agentId: job.agentId });
    if (job.wakeMode === "now") {
      state.deps.requestHeartbeatNow({ reason: `cron:${job.id}` });
    }
  }

  return { status: res.status, error: res.error, summary: res.summary };
}
```

> **Sidebar—Heartbeat**: In OpenClaw, a heartbeat is the Agent's "processing loop." The Agent doesn't run continuously—it wakes up when it receives a message or system event, processes it, then returns to sleep. `requestHeartbeatNow` requests the Agent to wake up immediately and process queued events; `runHeartbeatOnce` synchronously waits for one heartbeat to complete. The main-session mode of Cron wakes the Agent by injecting a system event and triggering a heartbeat, allowing the Agent to "see" the scheduled message.

### Isolated Agent Execution Details

`runCronIsolatedAgentTurn` (located in `src/cron/isolated-agent/run.ts`) is the core function for isolated execution. It accomplishes the following:

1. **Session management**—creates or reuses a session for each Cron run; session key format is `agent:{agentId}:cron:{jobId}`
2. **Model selection**—prioritizes the model specified in the job, falls back to Agent's default model
3. **Thinking level**—supports `thinking` override (low/medium/high/xhigh); models that don't support xhigh automatically downgrade
4. **Safety wrapping**—content from external hooks (e.g., Gmail) is safely wrapped to prevent prompt injection
5. **Delivery handling**—after Agent completes, sends results to specified channels according to delivery plan

```typescript
// src/cron/isolated-agent/run.ts — session key and label (simplified)

const baseSessionKey = params.sessionKey || `cron:${params.job.id}`;
const runSessionKey = baseSessionKey.startsWith("cron:")
  ? `${agentSessionKey}:run:${runSessionId}`
  : baseSessionKey;

// Auto-generate session label
if (!sessionEntry.label && baseSessionKey.startsWith("cron:")) {
  sessionEntry.label = `Cron: ${job.name || job.payload.message?.slice(0, 50)}`;
}
```

### Job Lifecycle

Complete job execution lifecycle:

```
armTimer() → setTimeout() → onTimer() → locked() → findDueJobs()
    │
    ├── Mark runningAtMs (prevent re-entry)
    ├── emit("started")
    │
    ├── executeJobCore()
    │   ├── main → enqueueSystemEvent + requestHeartbeat
    │   └── isolated → runIsolatedAgentJob + deliver summary
    │
    ├── Update state: lastRunAtMs, lastStatus, lastDurationMs
    ├── Compute nextRunAtMs
    │   ├── at type + ok → disable or delete
    │   └── every/cron type → compute next time
    │
    ├── emit("finished")
    ├── persist() → write to disk
    └── armTimer() → reset timer
```

Key state transitions:

* **After successful `at` type execution**: if `deleteAfterRun=true` delete the job, otherwise disable it (`enabled=false`)
* **`every`/`cron` types**: compute next run time based on end time, re-arm timer
* **Failed jobs**: record `lastError`, compute next run time normally (failure doesn't stop scheduling)

***

## 26.2.2 Delivery Plan (`src/cron/delivery.ts`)

After an isolated Cron job completes, the Agent's reply text needs to be **delivered** to the user—for example, sent to WhatsApp, Telegram, or injected into the main session. The Delivery Plan determines the delivery target and method.

### Delivery Configuration

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

export type CronDelivery = {
  mode: CronDeliveryMode;     // "announce" | "none"
  channel?: CronMessageChannel; // Channel ID (e.g., "whatsapp", "telegram") or "last"
  to?: string;                 // Target recipient
  bestEffort?: boolean;        // Silently ignore delivery failures
};
```

| `mode`       | Behavior                                 |
| ------------ | ---------------------------------------- |
| `"announce"` | Deliver Agent reply to specified channel |
| `"none"`     | Don't deliver (only record run result)   |

### Delivery Plan Resolution

`resolveCronDeliveryPlan` handles both new and legacy configuration formats:

```typescript
// src/cron/delivery.ts — resolveCronDeliveryPlan

export function resolveCronDeliveryPlan(job: CronJob): CronDeliveryPlan {
  const payload = job.payload.kind === "agentTurn" ? job.payload : null;
  const delivery = job.delivery;

  // New format: delivery object
  if (delivery) {
    const mode = delivery.mode ?? "announce";
    const channel = delivery.channel ?? payload?.channel ?? "last";
    const to = delivery.to ?? payload?.to;
    return {
      mode,
      channel,
      to,
      source: "delivery",
      requested: mode === "announce",
    };
  }

  // Legacy format: deliver/channel/to fields inside payload
  const legacyMode = payload?.deliver === true
    ? "explicit"
    : payload?.deliver === false ? "off" : "auto";
  const hasExplicitTarget = Boolean(to);
  const requested = legacyMode === "explicit"
    || (legacyMode === "auto" && hasExplicitTarget);

  return {
    mode: requested ? "announce" : "none",
    channel,
    to,
    source: "payload",
    requested,
  };
}
```

**`channel: "last"`** is a special value—it means "use the user's most recently active message channel." For example, if the user recently chatted with the Agent on WhatsApp, Cron delivery will be sent to WhatsApp.

***

## 26.2.3 Run Logs (`src/cron/run-log.ts`)

Every Cron job execution is logged to a JSONL-format run log.

### Log File Organization

```
~/.openclaw/cron/
├── jobs.json          # Job definitions
└── runs/
    ├── job-abc.jsonl   # Run log for job abc
    └── job-def.jsonl   # Run log for job def
```

Path resolution:

```typescript
// src/cron/run-log.ts — resolveCronRunLogPath

export function resolveCronRunLogPath(params: { storePath: string; jobId: string }) {
  const dir = path.dirname(params.storePath);  // Directory containing jobs.json
  return path.join(dir, "runs", `${params.jobId}.jsonl`);
}
```

### Log Entries

```typescript
export type CronRunLogEntry = {
  ts: number;           // Record timestamp
  jobId: string;        // Job ID
  action: "finished";   // Action type (currently only "finished")
  status?: "ok" | "error" | "skipped";  // Execution status
  error?: string;       // Error message
  summary?: string;     // Agent reply summary
  sessionId?: string;   // Isolated session ID
  sessionKey?: string;  // Session key
  runAtMs?: number;     // Actual start time
  durationMs?: number;  // Execution duration
  nextRunAtMs?: number; // Next scheduled run time
};
```

### Writing: Serialization + Auto-Pruning

```typescript
// src/cron/run-log.ts — appendCronRunLog

const writesByPath = new Map<string, Promise<void>>();

export async function appendCronRunLog(filePath: string, entry: CronRunLogEntry, opts?) {
  const resolved = path.resolve(filePath);
  // Serialize: queue writes to the same file sequentially
  const prev = writesByPath.get(resolved) ?? Promise.resolve();
  const next = prev.catch(() => undefined).then(async () => {
    await fs.mkdir(path.dirname(resolved), { recursive: true });
    await fs.appendFile(resolved, `${JSON.stringify(entry)}\n`, "utf-8");

    // Auto-prune: keep only recent 2000 lines when exceeding 2MB
    await pruneIfNeeded(resolved, {
      maxBytes: opts?.maxBytes ?? 2_000_000,
      keepLines: opts?.keepLines ?? 2_000,
    });
  });
  writesByPath.set(resolved, next);
  await next;
}
```

**Auto-pruning** prevents log files from growing indefinitely. When a file exceeds 2MB, only the most recent 2000 lines are kept. Pruning is implemented via "write to temp file → atomic rename," avoiding data loss if pruning is interrupted.

### Reading: Reverse Scan

```typescript
// src/cron/run-log.ts — readCronRunLogEntries

export async function readCronRunLogEntries(filePath, opts?): Promise<CronRunLogEntry[]> {
  const limit = Math.min(5000, opts?.limit ?? 200);
  const raw = await fs.readFile(filePath, "utf-8").catch(() => "");
  const parsed: CronRunLogEntry[] = [];
  const lines = raw.split("\n");

  // Scan from end (newest first)
  for (let i = lines.length - 1; i >= 0 && parsed.length < limit; i--) {
    const line = lines[i]?.trim();
    if (!line) continue;
    const obj = JSON.parse(line);
    if (obj.action !== "finished") continue;  // Only read "finished" entries
    parsed.push(entry);
  }

  return parsed.toReversed();  // Restore chronological order
}
```

Reverse scanning ensures that even for large files, only the most recent N records need to be read.

***

## 26.2.4 Cron Storage and Migration (`src/cron/store.ts`)

### Storage Format

All Cron jobs are stored in a single JSON file:

```json
{
  "version": 1,
  "jobs": [
    {
      "id": "abc-123",
      "name": "Daily News Summary",
      "enabled": true,
      "schedule": { "kind": "cron", "expr": "0 8 * * *", "tz": "Asia/Shanghai" },
      "sessionTarget": "isolated",
      "wakeMode": "now",
      "payload": { "kind": "agentTurn", "message": "Search for today's tech news and generate a summary" },
      "delivery": { "mode": "announce", "channel": "whatsapp" },
      "state": { "nextRunAtMs": 1709280000000, "lastStatus": "ok" },
      "createdAtMs": 1709000000000,
      "updatedAtMs": 1709200000000
    }
  ]
}
```

### Storage Path

```typescript
// src/cron/store.ts

export const DEFAULT_CRON_DIR = path.join(CONFIG_DIR, "cron");
export const DEFAULT_CRON_STORE_PATH = path.join(DEFAULT_CRON_DIR, "jobs.json");

export function resolveCronStorePath(storePath?: string) {
  if (storePath?.trim()) {
    const raw = storePath.trim();
    if (raw.startsWith("~")) {
      return path.resolve(raw.replace("~", os.homedir()));
    }
    return path.resolve(raw);
  }
  return DEFAULT_CRON_STORE_PATH;  // ~/.openclaw/cron/jobs.json
}
```

### Loading and Saving

```typescript
// src/cron/store.ts — loadCronStore

export async function loadCronStore(storePath: string): Promise<CronStoreFile> {
  try {
    const raw = await fs.promises.readFile(storePath, "utf-8");
    const parsed = JSON5.parse(raw);  // Supports JSON5 format (comments, trailing commas)
    const jobs = Array.isArray(parsed.jobs) ? parsed.jobs.filter(Boolean) : [];
    return { version: 1, jobs };
  } catch (err) {
    if (err.code === "ENOENT") {
      return { version: 1, jobs: [] };  // File doesn't exist → empty store
    }
    throw err;
  }
}
```

> **Sidebar—JSON5**: JSON5 is a superset of JSON that allows comments (`//` and `/* */`), trailing commas, single-quoted strings, multiline strings, etc. OpenClaw uses JSON5 to parse Cron storage, allowing users to manually edit `jobs.json` with friendlier syntax.

```typescript
// src/cron/store.ts — saveCronStore

export async function saveCronStore(storePath: string, store: CronStoreFile) {
  await fs.promises.mkdir(path.dirname(storePath), { recursive: true });

  // Atomic write: write to temp file, then rename
  const tmp = `${storePath}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
  await fs.promises.writeFile(tmp, JSON.stringify(store, null, 2), "utf-8");
  await fs.promises.rename(tmp, storePath);

  // Best-effort backup
  try {
    await fs.promises.copyFile(storePath, `${storePath}.bak`);
  } catch { /* ignore */ }
}
```

**Atomic writing** is implemented via "write to temp file → `rename`." On the same filesystem, `rename` is atomic, ensuring that even if the process crashes mid-write, the original file isn't corrupted. A `.bak` backup is created after each save.

### Gateway Integration

The Cron service is initialized when Gateway starts:

```typescript
// src/gateway/server-cron.ts — buildGatewayCronService (simplified)

export function buildGatewayCronService(params) {
  const storePath = resolveCronStorePath(params.cfg.cron?.store);
  const cronEnabled = process.env.OPENCLAW_SKIP_CRON !== "1"
    && params.cfg.cron?.enabled !== false;

  const cron = new CronService({
    storePath,
    cronEnabled,
    log: getChildLogger({ module: "cron" }),
    enqueueSystemEvent: params.enqueueSystemEvent,
    requestHeartbeatNow: params.requestHeartbeatNow,
    runHeartbeatOnce: params.runHeartbeatOnce,
    runIsolatedAgentJob: async ({ job, message }) => {
      return await runCronIsolatedAgentTurn({
        job,
        message,
        sessionKey: `cron:${job.id}`,
        lane: "cron",
        cfg: params.cfg,
        // ... more parameters
      });
    },
    onEvent: (evt) => {
      params.broadcast("cron", evt, { dropIfSlow: true });
      // Append run log after completion
      if (evt.action === "finished") {
        appendCronRunLog(logPath, { ...evt, ts: Date.now() });
      }
    },
  });

  return { cron, storePath, cronEnabled };
}
```

Key configuration:

* **`OPENCLAW_SKIP_CRON=1`**—environment variable completely disables Cron (no loading, no scheduling)
* **`cron.enabled: false`**—config file disables it (jobs saved but not scheduled)
* **`onEvent` broadcast**—every job state change is broadcast via WebSocket to all connected clients
* **`lane: "cron"`**—Cron jobs run on a dedicated command lane, isolated from main session

***

## Section Summary

1. Cron jobs have two execution modes: **main session** (inject system event + trigger heartbeat) and **isolated session** (independent Agent run)
2. Isolated Agent execution involves session management, model selection, thinking level control, safety wrapping, and delivery handling
3. **Delivery Plan** determines where isolated job results go; supports both new `delivery` object and legacy `payload` field configurations
4. Run logs use **JSONL format**, one file per job; writes are serialized to prevent races, auto-pruned to prevent unbounded growth
5. Job storage uses **JSON5 file** (`~/.openclaw/cron/jobs.json`), supports manual editing
6. Storage operations use **atomic writes** (temp file + rename) to ensure data safety; `.bak` backup created after each save
7. Gateway integration **broadcasts** Cron events via WebSocket to clients and appends run logs
