liveBook · Manning

After clause

As explained in Elixir in Action, Third Edition

An after clause is a receive construct that specifies an alternative branch to execute when no matching message arrives before a timeout.

An after clause gives receive a bounded wait. When no mailbox message matches its patterns within the specified time in milliseconds, the after branch executes instead of waiting indefinitely. section 5.2.2

Receive processes messages and timeout behavior in this order:

  • Searches the mailbox for the oldest message matching a receive pattern. section 5.2.2
  • Executes the matching branch and returns its last expression. section 5.2.2
  • Continues waiting when messages are absent or do not match, until the after timeout expires. section 5.2.2

Bounded receive

receive do message -> IO.inspect(message) after 5000 -> IO.puts("message not received") end With no matching message, the timeout branch prints its fallback after 5,000 milliseconds. section 5.2.2

iex(1)> receive do
          message -> IO.inspect(message)
        after
          5000 -> IO.puts("message not received")
        end
 
message not received    #1

Use the interactive example to see receive avoid an indefinite block and execute its timeout branch. section 5.2.2

How Elixir in Action, Third Edition covers it

How deep it goes
Explains timeout syntax, mailbox scanning, unmatched-message handling, and expression results through interactive examples.
Examples
Demonstrates a five-second timeout that prints a fallback when no matching message arrives.
What it assumes
Assumes receive patterns, process mailboxes, message arrival, and Elixir expression results.
What you can do after
Apply it via receive to handle absent messages without indefinite waiting.
How it connects
Connects receive expressions with message passing, pattern matching, process mailboxes, and asynchronous processes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.