> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_11_event_bus_and_scheduler/11.3_scheduler_timed_task_scheduling.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 11.3 Scheduler: Timed Task Scheduling

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generation Date**: 2026-02-17

***

In addition to event-driven real-time communication, OpenCode also requires some **periodic** background tasks -- for example, periodically cleaning up expired snapshot data or deleting outdated tool output files. These tasks do not need to execute immediately, but they need to run periodically to maintain system health. The `Scheduler` module provides a lightweight timed task scheduler for this purpose.

## 11.3.1 Scheduler.register() -- Task Registration

The complete implementation of Scheduler is only 62 lines of code, yet it covers the core functionality of task scheduling:

```typescript
// scheduler/index.ts
export namespace Scheduler {
  const log = Log.create({ service: "scheduler" })

  export type Task = {
    id: string                      // Unique task identifier
    interval: number                // Execution interval (milliseconds)
    run: () => Promise<void>        // Task execution function
    scope?: "instance" | "global"   // Scope
  }

  export function register(task: Task) {
    const scope = task.scope ?? "instance"
    const entry = scope === "global" ? shared : state()

    // Global tasks are only registered once
    const current = entry.timers.get(task.id)
    if (current && scope === "global") return

    // Instance tasks replace the old timer
    if (current) clearInterval(current)

    entry.tasks.set(task.id, task)

    // Execute immediately once
    void run(task)

    // Set up the periodic timer
    const timer = setInterval(() => {
      void run(task)
    }, task.interval)
    timer.unref()  // Critical: do not prevent process exit
    entry.timers.set(task.id, timer)
  }
}
```

The behavior of `register()` has the following characteristics:

**1. Immediate First Execution**: After registration, the task is executed immediately once (`void run(task)`) rather than waiting until the first interval period elapses. This ensures that initial cleanup is performed at system startup.

**2. Idempotent Registration**: For global tasks, if a task with the same ID has already been registered, `register()` returns immediately (`if (current && scope === "global") return`). For instance tasks, the old timer is cleared and the task is re-registered.

**3. `timer.unref()`**: This is an important API in Node.js. By default, active timers prevent the Node.js process from exiting -- the process will keep waiting until all timers are cleared. `unref()` tells the runtime "this timer is not important; do not keep the process alive because of it." This is especially important for CLI tools -- when the user presses Ctrl+C to exit, cleanup task timers should not prevent the process from terminating.

> **Extended Explanation: timer.unref() and the Event Loop**
>
> The event loop in Node.js (and Bun) continues to run as long as there are "pending asynchronous operations" -- including active timers, unfinished I/O, pending Promises, etc. When all operations are complete, the event loop exits and the process terminates.
>
> Timers created by `setInterval()` keep the event loop active by default. If a timer executes once per hour, the process will run for at least one hour before exiting.
>
> `timer.unref()` marks the timer as "not important" -- the event loop ignores it when deciding whether to exit. If there are no other pending operations besides `unref()`-ed timers, the process can exit immediately.

## 11.3.2 Instance-Level vs Global-Level Tasks

Scheduler supports two scopes, corresponding to different storage locations and lifecycles:

```typescript
// Global shared state (process lifetime)
const shared = create()

// Instance-level state (Instance lifetime)
const state = Instance.state(
  () => create(),               // Initialization: create new tasks + timers Maps
  async (entry) => {            // Cleanup: when Instance is destroyed
    for (const timer of entry.timers.values()) {
      clearInterval(timer)      // Clear all timers
    }
    entry.tasks.clear()
    entry.timers.clear()
  },
)
```

| Feature           | Instance Level                              | Global Level                   |
| ----------------- | ------------------------------------------- | ------------------------------ |
| Storage Location  | `Instance.state()`                          | Module-level variable `shared` |
| Lifetime          | Created/destroyed with the Instance         | Starts/ends with the process   |
| Re-registration   | Replaces old task (re-registration allowed) | Ignores duplicate registration |
| Multi-Instance    | Each Instance has an independent task set   | All Instances share one        |
| Automatic Cleanup | `clearInterval` on Instance destruction     | Reclaimed on process exit      |

Which scope to choose depends on the nature of the task:

* **Instance level** is suitable for tasks bound to a specific project (e.g., snapshot cleanup -- each project has its own snapshot repository).
* **Global level** is suitable for system-wide shared tasks (e.g., tool output cleanup -- all projects share the same output directory).

## 11.3.3 Error Handling: Silent Fault Tolerance

The task execution function is wrapped in a `catch` to ensure that a single execution failure does not affect subsequent scheduling:

```typescript
async function run(task: Task) {
  log.info("run", { id: task.id })
  await task.run().catch((error) => {
    log.error("run failed", { id: task.id, error })
  })
}
```

This "log the error but keep running" strategy is well-suited for cleanup tasks -- if a snapshot cleanup fails because the disk is temporarily unavailable, retrying an hour later will very likely succeed.

## 11.3.4 Practical Use Cases

As of the current version, Scheduler has two actively registered tasks:

### Snapshot Cleanup (Instance Level)

```typescript
// snapshot/index.ts
export function init() {
  Scheduler.register({
    id: "snapshot.cleanup",
    interval: 60 * 60 * 1000,  // Every hour
    run: cleanup,
    scope: "instance",
  })
}

export async function cleanup() {
  if (Instance.project.vcs !== "git") return
  const cfg = await Config.get()
  if (cfg.snapshot === false) return

  const git = gitdir()
  const exists = await fs.stat(git).then(() => true).catch(() => false)
  if (!exists) return

  // Use git gc to clean up objects older than 7 days
  await $`git --git-dir ${git} --work-tree ${Instance.worktree} gc --prune=7.days`
    .quiet().cwd(Instance.directory).nothrow()
}
```

Snapshot cleanup uses `git gc --prune=7.days` to remove Git objects older than 7 days. This task is Instance-level because each project has its own snapshot repository (see Section 10.1) and needs individual cleanup.

### Tool Output Cleanup (Global Level)

```typescript
// tool/truncation.ts
export function init() {
  Scheduler.register({
    id: "tool.truncation.cleanup",
    interval: 60 * 60 * 1000,  // Every hour
    run: cleanup,
    scope: "global",
  })
}

export async function cleanup() {
  const cutoff = Identifier.timestamp(
    Identifier.create("tool", false, Date.now() - 7 * 24 * 60 * 60 * 1000)
  )
  const glob = new Bun.Glob("tool_*")
  const entries = await Array.fromAsync(
    glob.scan({ cwd: DIR, onlyFiles: true })
  ).catch(() => [])

  for (const entry of entries) {
    if (Identifier.timestamp(entry) >= cutoff) continue
    await fs.unlink(path.join(DIR, entry)).catch(() => {})
  }
}
```

Tool output cleanup scans the `~/.local/share/opencode/tool-output/` directory and deletes output files older than 7 days. Recall from Chapter 5 that when a tool's output exceeds 2000 lines or 50KB, the full output is saved to a file, and a truncated version along with the file path is returned to the LLM. These temporary files need periodic cleanup.

This task is Global-level -- tool output from all projects is stored in the same directory, so only a single cleanup task is needed.

### Timing Diagram

```
Timeline -->

Start Instance A
  ├── register("snapshot.cleanup", instance)  // Instance A's snapshot cleanup
  ├── register("tool.truncation.cleanup", global)  // Global tool output cleanup
  └── Execute cleanup immediately once

1 hour later
  ├── snapshot.cleanup executes (Instance A's snapshot repository)
  └── tool.truncation.cleanup executes (global output directory)

Start Instance B (another project)
  ├── register("snapshot.cleanup", instance)  // Instance B has its own snapshot cleanup
  ├── register("tool.truncation.cleanup", global)  // Already exists, skip
  └── Execute Instance B's snapshot.cleanup immediately

Instance A is destroyed
  └── Automatically clearInterval(Instance A's snapshot.cleanup)
      // tool.truncation.cleanup is unaffected (global level)
```

## 11.3.5 Summary

The Scheduler module implements a fully functional timed task scheduler with minimal code (62 lines):

| Feature                   | Implementation                                                  |
| ------------------------- | --------------------------------------------------------------- |
| Immediate First Execution | `run(task)` immediately after registration                      |
| Periodic Execution        | `setInterval(fn, interval)`                                     |
| Non-Blocking Exit         | `timer.unref()`                                                 |
| Scope Isolation           | Instance level vs Global level                                  |
| Idempotent Registration   | Global tasks are not duplicated; instance tasks can be replaced |
| Automatic Cleanup         | `clearInterval` in `Instance.state()` destruction callback      |
| Error Tolerance           | `catch` + logging, does not interrupt subsequent scheduling     |

Compared to more complex task scheduling frameworks (such as `node-cron`), Scheduler lacks advanced features like cron expressions, priority queues, and dependency graphs. However, for OpenCode's current needs -- two cleanup tasks that run once per hour -- this minimalist design is exactly sufficient, without introducing unnecessary complexity. This embodies a design philosophy that recurs throughout the OpenCode codebase: **good enough is good enough; do not over-engineer**.
