Timers and timeouts
A timer in Erlang is a message that arrives later. Nothing blocks: the runtime keeps the clock, and the process that asked for the timer gets a message when it is due, in the same mailbox as every other message. That is why the four calls of this lesson all end in receive or in a callback, and why a selective receive is what makes several timers in one process manageable.
sleep
timer:sleep/1 suspends the calling process for a number of milliseconds and answers ok. It suspends one process, not the VM: the scheduler keeps running everything else, and a thousand processes can sleep at the same time. The program starts a process that sleeps for 50 milliseconds and sends the result of a message it sends itself at once, which shows the order:
sleepy.erl
-module(sleepy). -export([main/0]). main() -> Self = self(), spawn(fun() -> timer:sleep(50), Self ! {done, sleeper} end), Self ! {done, main}, io:format("first: ~p~n", [wait()]), io:format("second: ~p~n", [wait()]). wait() -> receive {done, Who} -> Who after 1000 -> timeout end.
erlc sleepy.erl
erl -noshell -eval 'sleepy:main(), halt().'
first: main second: sleeper
The only process that waited is the one that called sleep/1. Sleep belongs in a retry with backoff, in a test that waits for a process to settle, or in a demonstration like this one. It does not belong in a loop that waits for a message: receive ... after does the same job and wakes up at once when the message arrives.
send_after and cancel
erlang:send_after/3 puts a message in a mailbox after a delay and answers a reference, so the caller never blocks. erlang:cancel_timer/1 takes the reference and answers the milliseconds that were left, or false when the timer had already fired. The program uses both families of the API, the plain erlang one and the timer module that schedules a function call:
later.erl
-module(later). -export([main/0]). main() -> Ref = erlang:send_after(50, self(), ping), io:format("a reference: ~p~n", [is_reference(Ref)]), io:format("send_after: ~p~n", [wait(ping)]), Ref2 = erlang:send_after(50, self(), late), Left = erlang:cancel_timer(Ref2), io:format("cancelled with time left: ~p~n", [Left > 0]), io:format("after the cancel: ~p~n", [wait_short(late)]), {ok, TRef} = timer:apply_after(50, erlang, send, [self(), applied]), receive applied -> ok after 1000 -> timeout end, io:format("apply_after: ~p~n", [applied]), io:format("cancel of a fired timer: ~p~n", [timer:cancel(TRef)]). wait(Msg) -> receive Msg -> fired after 1000 -> timeout end. wait_short(Msg) -> receive Msg -> delivered after 200 -> timeout end.
erlc later.erl
erl -noshell -eval 'later:main(), halt().'
a reference: true send_after: fired cancelled with time left: true after the cancel: timeout apply_after: applied cancel of a fired timer: {ok,cancel}
A cancelled message never reaches the mailbox, which the fourth line proves: the short receive waited past the moment the message would have arrived and timed out. Keep the two families apart, because their references are not interchangeable. A reference from erlang:send_after/3 goes to erlang:cancel_timer/1, and timer:cancel/1 answers an error for it:
erl
1> timer:cancel(erlang:send_after(50, self(), x)). {error,badarg}
The mistake is easy to make because both families offer a cancel function and both take a reference. The one that belongs to the timer module, timer:cancel/1, takes the reference timer:apply_after/4 answered, and returns {ok, cancel} when the call had already been made.
start_timer
erlang:start_timer/3 is the variant that tells the receiver which timer fired: its message is the tuple {timeout, Ref, Msg}. One process can therefore keep several timers in flight and match on the reference, which is how a request timeout is written. The program starts a slow timer and a fast one, then waits for the slow one first:
ticker.erl
-module(ticker). -export([main/0]). main() -> Slow = erlang:start_timer(60, self(), slow), Fast = erlang:start_timer(30, self(), fast), io:format("waiting for the slow one: ~p~n", [wait(Slow)]), io:format("then the fast one: ~p~n", [wait(Fast)]). wait(Ref) -> receive {timeout, Ref, Msg} -> Msg after 1000 -> timeout end.
erlc ticker.erl
erl -noshell -eval 'ticker:main(), halt().'
waiting for the slow one: slow then the fast one: fast
The fast message arrived first and stayed in the mailbox while the process waited for the slow one, because the bound Ref in the pattern matches only its own timer. The second call then found its message already there. That is the whole mechanism of a per-request timeout: every request has its reference, and the clause that matches it is the answer to that request.
The timeout of a server
Inside a gen_server the same idea has a shorter form: return {noreply, State, Timeout} and the server calls handle_info(timeout, State) when no message arrives in that many milliseconds. The program counts pings and prints the counter from the timeout clause, which shows that the server woke up by itself:
gen_timeout.erl
-module(gen_timeout). -behaviour(gen_server). -export([main/0, ping/0, count/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2]). main() -> {ok, _Pid} = gen_server:start_link({local, ?MODULE}, ?MODULE, 0, []), ok = gen_server:cast(?MODULE, ping), ok = gen_server:cast(?MODULE, ping), timer:sleep(150), io:format("count: ~p~n", [count()]), ok = gen_server:stop(?MODULE). ping() -> gen_server:cast(?MODULE, ping). count() -> gen_server:call(?MODULE, count). init(N) -> {ok, N}. handle_call(count, _From, N) -> {reply, N, N}. handle_cast(ping, N) -> {noreply, N + 1, 100}. handle_info(timeout, N) -> io:format("idle after ~p pings~n", [N]), {noreply, N}.
erlc gen_timeout.erl
erl -noshell -eval 'gen_timeout:main(), halt().'
idle after 2 pings count: 2
Every cast reset the clock, so the timeout fired once, 100 milliseconds after the second ping, and the counter stayed at two. A clause that answers {noreply, State, hibernate} puts the process to sleep until the next message instead, which saves memory for a server that is idle most of the day. The timeout is not a timer reference in the state: the server owns it, and a call that answers {reply, ...} cancels it.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which process does
timer:sleep/1suspend?Answer
Only the calling process
Only the caller waits; every other process keeps running on the scheduler.
-
What does
erlang:send_after/3answer?Answer
A reference to the timer
The reference identifies the timer, and
erlang:cancel_timer/1takes it. -
What message does
erlang:start_timer/3deliver?Answer
{timeout, Ref, Msg}The tuple carries the reference, so several timers can share one mailbox.
-
What does
erlang:cancel_timer/1answer for a pending timer?Answer
The milliseconds left
The remaining time is useful for logging, and it is
falseonce the timer has fired. -
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
timeoutwhen nothing arrives in time. -
What does
timer:cancel/1answer when the call had already been made?Answer
{ok, cancel}The timer module reports a completed call with
{ok, cancel}. -
What does this module print?
-module(q1). -export([main/0]). main() -> Self = self(), spawn(fun() -> timer:sleep(30), Self ! {done, child} end), Self ! {done, main}, io:format("~p~n", [wait()]). wait() -> receive {done, Who} -> Who after 1000 -> timeout end.Answer
mainThe main process sends its message at once, while the child is still sleeping, so
mainis first in the mailbox. -
What does this module print?
-module(q2). -export([main/0]). main() -> Ref = erlang:send_after(50, self(), late), Left = erlang:cancel_timer(Ref), receive late -> delivered after 200 -> cancelled end, io:format("~p ~p~n", [Left > 0, cancelled]).Answer
true cancelledThe timer was cancelled before it fired, so time was left and the message never reached the mailbox.
-
What does this module print?
-module(q3). -export([main/0]). main() -> Slow = erlang:start_timer(50, self(), slow), Fast = erlang:start_timer(10, self(), fast), io:format("~p~n", [wait(Slow)]), io:format("~p~n", [wait(Fast)]). wait(Ref) -> receive {timeout, Ref, Msg} -> Msg after 1000 -> timeout end.Answer
slow/fastThe bound reference selects only its own timer, so the slow one is taken first and the fast message stays in the mailbox.
-
What does this module print?
-module(q4). -behaviour(gen_server). -export([main/0, count/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2]). main() -> {ok, _Pid} = gen_server:start_link({local, ?MODULE}, ?MODULE, 0, []), gen_server:cast(?MODULE, ping), timer:sleep(150), io:format("~p~n", [count()]), gen_server:stop(?MODULE). count() -> gen_server:call(?MODULE, count). init(N) -> {ok, N}. handle_call(count, _From, N) -> {reply, N, N}. handle_cast(ping, N) -> {noreply, N + 1, 100}. handle_info(timeout, N) -> {noreply, N + 1}.Answer
2The cast counts one ping and the idle timeout counts another, so the server holds two.
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.
Автор статьи: Arthur Isaev