How to gracefully kill gen_servers after their job is done?

If you want a dead-simple timeout that applies to the whole lifetime of a genserver you can also do something like this:

def init(_) do
  :timer.send_after(600_000, :job_timeout)
end

def handle_info(:job_timeout, state) do
  {:stop, :timeout, state}
end

Basically you send yourself a :job_timeout message 600 seconds after it starts. This timer won’t be reset by incoming messages. The only downside I know of is that :timer has a single process that sends all of the messages so if you get up to millions of jobs it can become a bottleneck.

3 Likes