# Timers and sleeping

> Durable sleeps, deadlines, and delayed calls.

Source: https://cairnflow.dev/docs/develop/timers

`ctx.sleep(ms)` pauses an invocation for a duration. The timer is stored durably; nothing holds a
process, a connection or memory while it waits, so sleeping for a week costs the same as sleeping
for a second.

```ts
await ctx.sleep(24 * 3600_000); // one day
```

```ts
sleep(ms: number, name?: string): DurableFuture<void>;
```

- The wake-up time is **absolute**: it is computed once, from the clock at the moment the sleep is
  first recorded, and stored in the journal. A replay does not start the timer again.
- `name` (default `"sleep"`) labels the entry in the journal and the console.
- When the sleep is not over yet, the turn ends and the invocation is **suspended**. It resumes when
  the timer fires, on whichever node owns it at that time.
- A timer fires at or shortly after its due time. Do not rely on millisecond precision.

## Deadlines with ctx.race

`ctx.sleep` returns a `DurableFuture`, so it combines with calls, signals, promises and awakeables.
`ctx.race` resolves with whichever finished first **in journal order**, so every replay picks the
same winner.

```ts
const approval = await ctx.race([
  ctx.signal<{ by: string }>("approve"),
  ctx.sleep(24 * 3600_000),
]);
if (approval === undefined) {
  throw new TerminalError("nobody approved within 24 hours", 408);
}
```

A sleep resolves to `undefined`, which is how you tell that the deadline won.

To tell two futures apart when their values could look alike, create both first, race them, then
compare their positions in the journal with `order()`:

```ts
const answer = ctx.promise<Decision>("approval").get();
const deadline = ctx.sleep(30 * 60_000, "approval deadline");
await ctx.race([answer, deadline]);
if (answer.order() > deadline.order()) {
  throw new TerminalError("approval timed out", 408);
}
const decision = await answer;
```

Do not use `ready()` for this: a late answer still lands in the journal, and from then on `ready()`
returns `true` on every replay, so the same code would take a different branch.

## Waiting for many things

`ctx.all([...])` waits for every future, like `Promise.all`, but suspends durably until all of them
are done. If one of them failed, it throws that failure.

```ts
const [a, b] = await ctx.all([
  ctx.call<string>("Search", "query", "a"),
  ctx.call<string>("Search", "query", "b"),
]);
```

## Delayed calls

To run another handler later instead of waiting yourself, send it with a delay. The handler that
sends it does not wait and does not hold a key:

```ts
ctx.send("Reminders", "remind", { userId }, { delay: 3 * 24 * 3600_000 });
```

Like a sleep, the due time is computed once and recorded. Delays are only available from inside a
handler; the client has no delayed send. For recurring work, use
[server-side schedules](/docs/develop/schedules).

## Reading the clock

Do not call `Date.now()` in the handler body: a replay would see a different time and could take a
different path. Read it inside a step:

```ts
const startedAt = await ctx.run("now", () => Date.now());
```

## Gotchas

- **A losing sleep still fires.** In a `race`, the sleep that loses keeps its timer and costs one
  durable write when it fires. Use long deadlines; do not poll with a loop of short sleeps.
- **Sleeping in an exclusive handler holds the key.** Other exclusive calls on the same virtual
  object wait until the sleep is over. Put long waits in a workflow or a plain service when the
  key must stay available.
- **Long loops grow the journal.** A loop that sleeps and polls forever adds entries every round.
  Restart it with a fresh journal from time to time with `ctx.continueAsNew(state)` — see
  [Deploying new versions](/docs/develop/versioning#long-running-loops).
- Your environment may limit the number of pending timers per invocation; on Cairnflow Cloud, see
  [Beta limits](/docs/cloud/limits).
