Skip to content

Instantly share code, notes, and snippets.

@minhajuddin
Created July 18, 2018 14:56
Show Gist options
  • Save minhajuddin/29b81ca83f1231fca397b769c13f0624 to your computer and use it in GitHub Desktop.
Save minhajuddin/29b81ca83f1231fca397b769c13f0624 to your computer and use it in GitHub Desktop.
defmodule SearchWorker do
use GenServer
@idle_timeout_ms 10 * 60 * 1000
# client api
def touch(pid) do
GenServer.cast(pid, :touch)
end
@impl GenServer
def init(_opts) do
state = touch_idle_timer(%{})
{:ok, state}
end
@impl GenServer
def handle_cast(:touch, state) do
# cancel current timer
Process.cancel_timer(state.idle_timer)
# create a new timer
state = touch_idle_timer(state)
{:noreply, state}
end
def handle_info(:idle_timeout, state) do
# do whatever you want to do to cleanup your process tree
shutdown_proc_tree(state)
{:noreply, state}
end
defp touch_idle_timer(state) do
# send ourselves a message after 10 seconds and cleanup the proc tree when we get this
idle_timer = Process.send_after(self(), :idle_timeout, @idle_timeout_ms)
%{state | idle_timer: idle_timer}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment