receive ... after in Erlang
after puts a clock on receive.
%% after puts a clock on receive: no message, take the timeout arm.
main(_) ->
%% Nobody ever calls, so the timeout arm answers.
receive
{call, Line} -> io:format("Ring on ~p~n", [Line])
after 50 ->
io:format("Quiet board, going to lunch~n")
end,
%% A message already waiting wins over the clock.
self() ! {call, 3},
receive
{call, L} -> io:format("Caught line ~p in time~n", [L])
after 1000 ->
io:format("Never reached~n")
end.
How it works
- No matching message by the deadline: the after arm runs.
- A waiting message always beats the clock.
self() ! Msgqueues a message to your own mailbox.
Keywords and builtins used here
afterendformatmainreceive
The run, in numbers
- Lines
- 16
- Characters to type
- 429
- Tokens
- 94
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 94 seconds.
Step 2 of 4 in Processes, step 26 of 31 in Language basics.