Skip to content

Commit 9a2cf51

Browse files
dmitrykleymenovggVGc
authored andcommitted
Add gen_server timeout example (elixir-lang#14530)
1 parent 0ec48a2 commit 9a2cf51

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

lib/elixir/lib/gen_server.ex

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,41 @@ defmodule GenServer do
349349
message arriving, `handle_info/2` is called with `:timeout` as the first
350350
argument.
351351
352+
For example:
353+
354+
defmodule Counter do
355+
use GenServer
356+
357+
@timeout to_timeout(second: 5)
358+
359+
@impl true
360+
def init(count) do
361+
{:ok, count, @timeout}
362+
end
363+
364+
@impl true
365+
def handle_call(:increment, _from, count) do
366+
new_count = count + 1
367+
{:reply, new_count, new_count, @timeout}
368+
end
369+
370+
@impl true
371+
def handle_info(:timeout, count) do
372+
{:stop, :normal, count}
373+
end
374+
end
375+
376+
A `Counter` server will exit with `:normal` if there are no messages in 5 seconds
377+
after the initialization or after the last `:increment` call:
378+
379+
{:ok, counter_pid} = GenServer.start(Counter, 50)
380+
GenServer.call(counter_pid, :increment)
381+
#=> 51
382+
383+
# After 5 seconds
384+
Process.alive?(counter_pid)
385+
#=> false
386+
352387
## When (not) to use a GenServer
353388
354389
So far, we have learned that a `GenServer` can be used as a supervised process

0 commit comments

Comments
 (0)