Skip to content

Instantly share code, notes, and snippets.

@ricardoccpaiva
Created March 14, 2021 18:30
Show Gist options
  • Save ricardoccpaiva/914f7713734517947839d547a47034b9 to your computer and use it in GitHub Desktop.
Save ricardoccpaiva/914f7713734517947839d547a47034b9 to your computer and use it in GitHub Desktop.
GenServer Timeout
defmodule Caller do
use GenServer
@spec start_link(list(any())) :: GenServer.on_start()
def start_link(default) when is_list(default) do
GenServer.start_link(__MODULE__, default)
end
def call do
Server.call
end
@impl true
def init(_arg) do
Process.flag(:trap_exit, true)
Process.register(self(), :caller)
{:ok, %{}}
end
@impl true
def handle_info(msg, state) do
IO.puts("-------> #{msg}")
{:noreply, state}
end
@impl true
def terminate(reason, state) do
IO.puts("-------> TERMINATE CALLER")
:ok
end
end
defmodule Server do
use GenServer
# Client
@spec start_link(list(any())) :: GenServer.on_start()
def start_link(default) when is_list(default) do
GenServer.start_link(__MODULE__, default)
end
def call do
response =
Process.whereis(:worker)
|> GenServer.call(:fetch)
end
# Server (callbacks)
@impl true
def init(_arg) do
Process.flag(:trap_exit, true)
Process.register(self(), :worker)
{:ok, %{}}
end
@impl true
def handle_info(msg, state) do
IO.puts("-------> #{msg}")
{:noreply, state}
end
def terminate(reason, state) do
IO.puts("-------> TERMINATE SERVER")
:ok
end
@impl true
def handle_call(:fetch, _from, state) do
IO.puts("------> SNAITAS")
:timer.sleep(6000)
{:reply, :ok, state}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment