liveBook · Manning

Handle_info/2

As explained in Elixir in Action, Third Edition

handle_info/2 is a GenServer callback that processes ordinary messages and system notifications not handled as calls or casts.

GenServer reserves handle_info/2 for messages outside its call and cast protocols, such as periodic maintenance signals or process-level notifications. section 6.2.4

Use the callback to:

  • Receive an ordinary message and update state, commonly returning {:noreply, new_state}. section 6.2.4
  • Handle an idle timeout represented by :timeout and stop an inactive server with {:stop, :normal, state}. section 10.2.4

Periodic cleanup

Schedule :cleanup with :timer.send_interval/2 during init/1, then match it in handle_info(:cleanup, state), perform cleanup, and return {:noreply, state}. section 6.2.4

Listing 10.6 Stopping an idle to-do server (todo_cache_expiry/lib/todo/server.ex)
defmodule Todo.Server do
  ...
 
  def handle_info(:timeout, {name, todo_list}) do
    IO.puts("Stopping to-do server for #{name}")
    {:stop, :normal, {name, todo_list}}           #1
  end
end

See the minimal callback that stops a to-do server after its idle timeout. section 10.2.4

How Elixir in Action, Third Edition covers it

How deep it goes
Explains message matching, state-returning tuples, periodic cleanup, and idle shutdown without detailing GenServer internals.
Examples
Uses five-second cleanup messages and a ten-second idle to-do-server shutdown.
What it assumes
Assumes familiarity with GenServer callbacks, init/1, state tuples, and call-versus-cast message handling.
What you can do after
Operate GenServer processes that perform periodic work or terminate after inactivity.
How it connects
Connects GenServer with handle_cast/2, handle_call/3, init/1, and Agent limitations.

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.