# Timers, selective receive and hibernate
Three BEAM tools for processes that wait: timers (`erlang:send_after`, gen_server's `timeout`),
selective receive (`receive ... after`), and `hibernate`. All of them run on the node's executor
clock, so a node on a `TestExecutor` drives them with virtual time (`exec.advance(d)`).
## Timers: `send_after` and `cancel_timer`
`ProcessCtx::send_after::<Self>(msg, d)` delivers `msg` to the process's own `handle_info` (as
`Info::User(msg)`) after `d` and returns a `TimerRef`. Callers outside the process use
`Addr::send_after(msg, d)`.
```rust,ignore
fn handle_info(mut self, msg: Info<Msg>, ctx: ProcessCtx) -> Effect<Next<Self>, Never, ()> {
if let Info::User(Msg::Tick) = msg {
self.ticks += 1;
self.next = Some(ctx.send_after::<Self>(Msg::Tick, Duration::from_millis(10)));
}
succeed(Next::Continue(self))
}
// later, in a handler:
- **Cancel is exact.** `ctx.cancel_timer(timer)` (or `timer.cancel()`) returns `true` when the
timer was pending: its message will never be delivered. `false` means it already fired or was
cancelled before. Firing and cancelling race on one atomic state, so exactly one wins. A
cancelled timer's task ends at once, not at the deadline.
- **Timers die with their process.** When the process exits, for any reason, its pending timers
are cancelled; `Addr::send_after` to a dead process returns an inert timer
(`is_pending() == false`).
- **A timer message is a user message.** It counts against the mailbox bound when it fires
(decision D17): a full mailbox drops it, exactly like `Addr::send_now`. Exit signals and
monitor downs still bypass the bound.
- `send_after::<P>` names the behavior because `ProcessCtx` is untyped; inside a callback it is
`Self`. With another behavior the timer is inert.
## Idle timeout: `Info::Timeout`
`ctx.set_idle_timeout(d)` makes the loop deliver `Info::Timeout` to `handle_info` when it has
waited `d` for the next message. It fires **once per idle period**: after a timeout the loop waits
without a deadline until a message arrives, and that message starts a new period.
`ctx.clear_idle_timeout()` removes it. The timeout never enters the mailbox, so a full mailbox
cannot hold it back, and no message is lost to the deadline: a message that arrives as the
deadline passes stays queued.
## Selective receive
`ctx.receive::<Self, _>(matcher, timeout)` takes the first message in the mailbox that
`matcher` accepts and leaves every skipped message queued, in arrival order, for the normal loop.
It fails with `ReceiveError::Timeout` once `timeout` passes, `ReceiveError::ScanLimit` once a
mailbox capacity's worth of messages was skipped, and `ReceiveError::Closed` when the process is
being killed. A matched `ProcMsg::Call` must be answered through its reply.
```rust,ignore
let reply = ctx