From edb93ce9e520f5765dc727bb084bdbd0e2ef01d7 Mon Sep 17 00:00:00 2001 From: dmitrykleymenov Date: Sun, 25 May 2025 13:06:07 +0300 Subject: [PATCH 1/3] Add gen_server `timeout` example --- lib/elixir/lib/gen_server.ex | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/lib/elixir/lib/gen_server.ex b/lib/elixir/lib/gen_server.ex index 6c4498b029e..42069ee784e 100644 --- a/lib/elixir/lib/gen_server.ex +++ b/lib/elixir/lib/gen_server.ex @@ -349,6 +349,42 @@ defmodule GenServer do message arriving, `handle_info/2` is called with `:timeout` as the first argument. + For example: + + defmodule Counter do + use GenServer + + @timeout 5000 + + @impl true + def init(count) do + {:ok, count, @timeout} + end + + @impl true + def handle_call(:succ, _from, count) do + new_count = count + 1 + {:reply, new_count, new_count, @timeout} + end + + @impl true + def handle_info(:timeout, count) do + {:stop, :normal, count} + end + end + + A `Counter` server will exit with `:normal` if there are no messages in 5 seconds + after the initialization or after the last `succ` call: + + + {:ok, counter_pid} = GenServer.start(Counter, 50) + GenServer.call(counter_pid, :succ) + #=> 51 + + # After 5 secs + Process.alive?(counter_pid) + #=> false + ## When (not) to use a GenServer So far, we have learned that a `GenServer` can be used as a supervised process From 3d9f3fbd82d558e1ad1619efe6bb1de28a7d0c79 Mon Sep 17 00:00:00 2001 From: dmitrykleymenov Date: Sun, 25 May 2025 13:13:59 +0300 Subject: [PATCH 2/3] Remove empty line --- lib/elixir/lib/gen_server.ex | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/elixir/lib/gen_server.ex b/lib/elixir/lib/gen_server.ex index 42069ee784e..bcb9816c697 100644 --- a/lib/elixir/lib/gen_server.ex +++ b/lib/elixir/lib/gen_server.ex @@ -376,7 +376,6 @@ defmodule GenServer do A `Counter` server will exit with `:normal` if there are no messages in 5 seconds after the initialization or after the last `succ` call: - {:ok, counter_pid} = GenServer.start(Counter, 50) GenServer.call(counter_pid, :succ) #=> 51 From 86322929623af9c8108778ba472e95199648c730 Mon Sep 17 00:00:00 2001 From: Dmitry Kleymenov Date: Sun, 25 May 2025 21:01:10 +0300 Subject: [PATCH 3/3] Update lib/elixir/lib/gen_server.ex Co-authored-by: Jean Klingler --- lib/elixir/lib/gen_server.ex | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/elixir/lib/gen_server.ex b/lib/elixir/lib/gen_server.ex index bcb9816c697..522c9000e28 100644 --- a/lib/elixir/lib/gen_server.ex +++ b/lib/elixir/lib/gen_server.ex @@ -354,7 +354,7 @@ defmodule GenServer do defmodule Counter do use GenServer - @timeout 5000 + @timeout to_timeout(second: 5) @impl true def init(count) do