Time out a receive with an after clause in Erlang
Stop a selective receive from waiting forever by adding an after clause with a timeout in milliseconds, using Erlang/OTP 27.
A bare receive blocks until a matching message arrives, which is a hang if the sender died. The after clause gives it a deadline in milliseconds and a fallback branch. Erlang/OTP 27.
-module(wait).
-export([run/0]).
run() ->
Self = self(),
spawn(fun() -> timer:sleep(200), Self ! late end),
receive
ready -> got_ready
after 50 ->
timed_out
end.1> wait:run().
timed_outThe late message is not ready, so it would never match anyway, but note what happens to it: it arrives after the receive has returned and stays in the mailbox. A timed-out call does not remove it, which is how mailboxes grow in long-lived processes. Two special values matter. after 0 makes the receive non-blocking, a way to poll the mailbox once. after infinity is the same as having no clause. The timeout restarts for each receive expression, and a message that does not match the patterns does not reset it. See the receive expression in the reference manual.