I have been fighting this for days and would appreciate some insight.
My mission is to set a timeout on each GenServer I create so that once a created GenServers pid wasn’t being called anymore it would automatically terminate itself.
I pasted my code below and the GenServers timeout is set to be 10 seconds.
Yet when I use code below, I create 2 GenServers by running the code in iex
–>
#####################
Stak.start_link(8)
Stak.start_link(9) # I wait 5 seconds to type this line
#####################
Yet 10 seconds after I type “Stak.start_link(8)”, both of the pid’s from the 2 lines I types terminate at the same time. Grrrr
Another mystery to me is if I type the lines:
#####################
Stak.start_link(8)
Stak.get_state(8) # type this line before 10 seconds pass
#####################
the pid from “Stak.start_link(8)” never timeouts or terminates, which I expected to happen 10 seconds after I typed “Stak.get_state(8)”
#####################################
######### My Code ###################
#####################################
defmodule Stak do
use GenServer
def start_link(event_id) do
name = via_tuple(event_id)
GenServer.start_link(__MODULE__, %{}, name: name)
end
defp via_tuple(event_id) do
{:via, Registry, {Registry.Runningevents, event_id}}
end
def set_timer(event_id, timer_config) do
GenServer.call(via_tuple(event_id), {:set_timer, timer_config})
end
def start_timer(event_id) do
GenServer.cast(via_tuple(event_id), {:start})
end
def get_state(event_id) do
name = via_tuple(event_id)
IO.inspect(name)
GenServer.call(name, {:get_state})
end
def get_pid(event_id) do
[{pid, nil}] = Registry.lookup(Registry.Runningevents, event_id)
pid
end
def init(state) do
### this lets us call :time_out and terminate. It will now terminate gracefully
Process.flag(:trap_exit, true)
IO.puts("The server Started")
IO.inspect(state)
{:ok, state, 10000}
end
def terminate(reason, state) do
IO.inspect(state)
IO.inspect(reason)
IO.puts("The server terminated")
IO.puts("#{__MODULE__}.terminate/2 called wit reason: #{inspect(reason)}")
end
################################## server api ##################################
def handle_call({:get_state}, _from, state) do
IO.inspect("The state")
IO.inspect(state)
{:reply, state, state}
end
def handle_info(:timeout, new_state) do
IO.inspect(new_state)
IO.inspect("time out")
{:stop, :timeout, new_state}
end
def handle_call({:set_timer, timer_config}, _from, state) do
IO.inspect(timer_config)
IO.inspect(state)
{:reply, timer_config, timer_config}
end
end























