Elixir foundationSort Order

Elixir: Gracefully Shutting Down GenServer Process - [026]

Now that we're done with the rendering process. We need to make sure we shutdown our GenServer gracefully. In this episode we'll take a look at using the terminate callback in GenServer to implement some of our clean up tasks.

Terminate Callback

defmodule Botiful.Render.Engine do  # ...  def stop(pid)    GenServer.stop(pid, :normal)  end  # ...  def terminate(:normal, state) do    PageSession.unsubscribe_all(state.conn)    PageSession.stop(state.conn)  endend

We will also add a bit of logging to our terminate function.

Adding Logging

We need to require logger in our GenServer before we can call Logger.info

defmodule Botiful.Render.Engine do  # ...  require Logger  def init(url) do    # ...    {:ok, %{      # add url to the init state so we can reference it later      url: url      # ...    }}  end    # ...  def terminate(:normal, state) do    # we reference the state.url we passed into the init callback    Logger.info("[Engine] Stopping Engine for #{state.url}")     PageSession.unsubscribe_all(state.conn)    PageSession.stop(state.conn)  endend

That's pretty much it for this episode! Now we have logging when we gracefully shutdown our render engine.