---
title: Schedule a handler
description: Run a luna's handler later, at a set time or on a cron, and choose what happens to runs that are missed or overlap.
related:
  - /background/run-durable-work
  - /lunas/call-another-luna
  - /sdk/ctx
---

A luna sleeps between calls, so nothing runs in it until something wakes it. A schedule runs one of its handlers at a time you choose, and wakes the luna to do it.

## Run a handler later

[`ctx.schedule`](/sdk/ctx) takes a handler's name, its arguments and when to run it. It returns the schedule's id.

```ts luna/lunas/list.ts
import { defineLuna, t, table } from "luna";

export const List = defineLuna({
  name: "List",
  key: { id: t.string() },
  schema: { items: table({ id: t.id(), text: t.string(), done: t.bool() }) },
  handlers: (h) => ({
    add: h({ args: { text: t.string() } }, (ctx, { text }) => {
      const item = ctx.db.items.insert({ text, done: false });
      ctx.schedule({ after: "1d", handler: "remind", args: { item } });
    }),
    remind: h({ args: { item: t.int() } }, (ctx, { item }) => {
      const row = ctx.db.items.get(item);
      if (row && !row.done) console.log(`Still to do: ${row.text}`);
    }),
  }),
});
```

The schedule is stored with the handler's writes. If the handler fails, the schedule goes with them. Luna checks the handler's name and arguments when you schedule it, not when it runs.

A scheduled run that fails is retried as a [message](/lunas/call-another-luna) is, 10 times over about a day.

## Pick when it runs

Give one of these options.

| Option | Does |
| --- | --- |
| `after` | Runs once after a delay in `ms`, `s`, `m`, `h` or `d`, such as `"10m"`, or a number of milliseconds |
| `at` | Runs once at a `Date`, or at a number of milliseconds since 1970 |
| `cron` | Runs again and again, on a cron expression |

```ts luna/lunas/list.ts
ctx.schedule({ at: new Date("2027-01-04T09:00:00Z"), handler: "remind", args: { item } });
```

## Repeat on a cron

`cron` takes five fields: minute, hour, day of the month, month and day of the week. Fields take lists, ranges, steps such as `*/15`, and the names `jan` to `dec` and `sun` to `sat`.

```ts luna/lunas/list.ts
ctx.schedule({ id: "digest", cron: "0 9 * * mon-fri", tz: "Europe/London", handler: "digest" });
```

`tz` is a time zone name, and `UTC` by default. A time that a clock change skips runs when the gap ends, and a time that happens twice runs once.

`cron` also takes `every` and a delay of at least 1 second, such as `"every 10m"`. It first runs one whole interval after you schedule it.

Each luna runs a cron up to a minute after the time it names, or within the interval of a shorter `every`, so lunas with the same cron do not all run at once.

## Replace a schedule by its id

Each call to `ctx.schedule` adds a schedule. Give an `id`, and scheduling the same id again replaces the one before. This pushes a tidy back by a week each time the list is touched.

```ts luna/lunas/list.ts
touch: h({}, (ctx) => {
  ctx.schedule({ id: "tidy", after: "7d", handler: "tidy" });
}),
```

Ids that start with `cron:` belong to the luna type's crons, and `ctx.schedule` refuses them.

## List, move and cancel schedules

`ctx.schedules` holds the luna's schedules.

| Method | Does |
| --- | --- |
| `list()` | Returns every schedule, with its handler, arguments, cron, time zone and `nextRunMs` |
| `reschedule(id, at)` | Moves a one-off schedule to a `Date` or a number of milliseconds, and returns false if there is none. A cron cannot be moved: schedule it again with the same id |
| `cancel(id)` | Deletes a schedule, and returns false if there is none |

```ts luna/lunas/list.ts
snooze: h({ args: { until: t.int() } }, (ctx, { until }) => {
  for (const s of ctx.schedules.list()) {
    if (s.handler === "remind") ctx.schedules.reschedule(s.id, until);
  }
}),
```

## Run a handler on another luna

`target` names another luna. The schedule is kept by the luna that made it, and goes to the target as a message when it is due.

```ts luna/lunas/shop.ts
renew: h({ args: { amount: t.int() } }, (ctx, { amount }) => {
  ctx.schedule({ after: "30d", target: { luna: Wallet, key: { id: ctx.key.id } }, handler: "charge", args: { amount } });
}),
```

## Declare crons on the luna type

The `crons` option of [`defineLuna`](/sdk/define-luna) gives every luna of the type the same cron. Each luna runs it on its own.

```ts luna/lunas/list.ts {1-3}
crons: {
  nightly: { schedule: "0 3 * * *", handler: "tidy" },
},
handlers: (h) => ({
  tidy: h({}, (ctx) => {
    ctx.db.items.delete({ where: { done: true } });
  }),
}),
```

A cron takes `schedule`, `handler`, `args`, `tz`, `onMissed` and `overlap`. It runs only in lunas that exist, so a key that was never written to has none. A deploy that changes or removes a cron reaches each luna as it moves to the new version. `ctx.schedules.list()` shows the cron as `cron:nightly`, with `typeLevel: true`, and `cancel` refuses it.

## Choose what happens to missed runs

A cron misses runs when its luna could not run at those times. `onMissed` says what happens once it can. With `once` and `skip`, Luna writes a line to the luna's [logs](/observe/read-logs) saying how many runs were missed.

| Value | Does |
| --- | --- |
| `"once"` | Runs once for all the missed runs. The default |
| `"skip"` | Runs the latest missed run if it is at most a minute late, and skips the rest |
| `"all"` | Runs every missed run, in order |

```ts luna/lunas/list.ts
ctx.schedule({ id: "count", cron: "every 1h", onMissed: "all", handler: "count" });
```

## Choose what happens when runs overlap

A cron's last run may still be going, or waiting to be retried, when the next one is due. `overlap` decides. A failed cron run is retried only until the next run is due.

| Value | Does |
| --- | --- |
| `"skip"` | Skips the new run, and writes a line to the logs. The default |
| `"queue"` | Runs the new one once the last one finishes |
| `"allow"` | Runs both at once |

```ts luna/lunas/list.ts
ctx.schedule({ id: "sync", cron: "*/5 * * * *", overlap: "queue", handler: "sync" });
```

## Know a call came from a schedule

In a scheduled run, `ctx.caller` is `{ schedule: true }`. `ctx.fire` says which schedule fired, when it was due and how late it ran. It is null for every other call.

```ts luna/lunas/list.ts
remind: h({ args: { item: t.int() } }, (ctx, { item }) => {
  if (!ctx.fire) return;
  console.log(`${ctx.fire.scheduleId} was due at ${ctx.fire.scheduledForMs} and ran ${ctx.fire.lateByMs} ms late`);
}),
```

In Python, `ctx.schedule` takes the handler first. See [Write lunas in Python](/lunas/write-lunas-in-python).

## Next steps

- [Run durable work](/background/run-durable-work) keeps a long job going through sleeps, waits and crashes.
- [Read logs](/observe/read-logs) shows the lines Luna writes about missed and skipped runs.
- [ctx](/sdk/ctx) lists every option of `ctx.schedule`.
