Skip to content

Instantly share code, notes, and snippets.

@axelson
Created May 8, 2023 20:24
Show Gist options
  • Save axelson/9f5ac9f48af10351ef278a4976561da2 to your computer and use it in GitHub Desktop.
Save axelson/9f5ac9f48af10351ef278a4976561da2 to your computer and use it in GitHub Desktop.
defmodule MyApp.GracefulShutdownHandler do
use GenServer
require Logger
def start_link(opts \\\\ []) do
GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end
@impl GenServer
def init(_init_arg) do
# We need to trap exits so that we receive the `terminate/2` callback during
# a graceful shutdown
Process.flag(:trap_exit, true)
{:ok, []}
end
# NOTE: We cannot guarantee that this will run on every shutdown, it will only
# get run on graceful shutdowns such as via a SIGTERM
@impl GenServer
def terminate(_reason, _state) do
Logger.info("Graceful Shutdown occurring")
:ok
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment