Timers and timeouts

sleep

timer:sleep suspends the calling process for a number of milliseconds and answers ok. It suspends one process, not the VM: a thousand processes can sleep at the same time and the scheduler keeps running everything else.

erl

1> timer:sleep(10).
ok

Sleep belongs in a retry with backoff, in a test that waits for a process to settle, or in a demo like this one. It does not belong in a loop that waits for a message: receive with an after clause does the same job and wakes up at once when the message arrives.

send_after

erlang:send_after puts a message in a mailbox after a delay and returns a reference, so the sender never blocks. The receive below waits for that message with a longer timeout as a safety net. Save this module as later.erl.

-module(later). -export([fire/1, cancel/0]). fire(Msg) -> erlang:send_after(50, self(), Msg), receive Msg -> fired after 1000 -> timeout end. cancel() -> Ref = erlang:send_after(50, self(), too_late), _Left = erlang:cancel_timer(Ref), receive too_late -> delivered after 200 -> cancelled end.

erlc later.erl
erl

1> timer:sleep(10).
ok
2> later:fire(ping).
fired
3> later:cancel().
cancelled

The timer runs in the background of the VM, so the message arrives while the process does something else, or while it waits. A busy process still gets the message, because the timer delivers it to the mailbox and not to a callback.

start_timer

erlang:start_timer is the variant that tells you which timer fired. The message is the tuple {timeout, Ref, Msg}, so one process can keep several timers in flight and match on the reference. That is how a request timeout is usually written.

erl

1> Ref = erlang:start_timer(50, self(), tick), ok.
ok
2> receive {timeout, Ref, Msg} -> Msg after 1000 -> timeout end.
tick

Inside a gen_server the same idea has a shorter form: return {noreply, State, 1000} and the server calls handle_info(timeout, State) if nothing else arrives in that second. Return {noreply, State, hibernate} to let the process sleep until the next message.

Cancel a timer

erlang:cancel_timer takes the reference and answers the milliseconds that were left, or false when the timer had already fired. A cancelled message never reaches the mailbox, which the receive below proves by waiting past the moment it would have arrived.

erl

1> Ref = erlang:send_after(100, self(), late), erlang:cancel_timer(Ref) > 0.
true
2> receive late -> delivered after 200 -> cancelled end.
cancelled

The timer module wraps the same calls for scheduling a function: timer:apply_after(Time, Module, Function, Args) and timer:cancel(TRef). Keep the two families apart, because a reference from erlang:send_after belongs to erlang:cancel_timer, and timer:cancel answers {error, badarg} for it.

Next: Code loading

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which process does timer:sleep/1 suspend?

    Answer

    Only the calling process

    Only the caller waits; every other process keeps running on the scheduler.

  2. What does erlang:send_after/3 return?

    Answer

    A reference to the timer

    The reference identifies the timer, which erlang:cancel_timer/1 then takes.

  3. What does erlang:send_after/3 do while it waits?

    Answer

    Nothing: the message arrives later

    The timer runs in the VM, so the caller goes on working or waiting for other messages.

  4. What message does erlang:start_timer/3 deliver?

    Answer

    {timeout, Ref, Msg}

    The tuple carries the reference, so several timers can share one mailbox.

  5. Why does the example match {timeout, Ref, Msg} with a bound Ref?

    Answer

    To check which timer fired

    The bound reference only matches the message of that particular timer.

  6. What does erlang:cancel_timer/1 answer for a pending timer?

    Answer

    The milliseconds left

    The remaining time is useful for logging, and it is false once the timer has fired.

  7. What happens to the message of a cancelled timer?

    Answer

    It never reaches the mailbox

    Cancellation removes the timer, so the receive waits out its own timeout instead.

  8. Which return value makes a gen_server call handle_info(timeout, State)?

    Answer

    {noreply, State, 1000}

    The third element is a timeout, and the server sends itself timeout when nothing arrives in time.

  9. Which function schedules a function call after a delay?

    Answer

    timer:apply_after/4

    timer:apply_after runs a module function later, and timer:cancel takes its reference.

  10. Why does timer:cancel/1 answer {error, badarg} for a send_after reference?

    Answer

    The reference belongs to the erlang timer family

    The two families keep separate references, so a send_after timer is cancelled with erlang:cancel_timer/1.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image