astery

astery

Ideally I want to create a gen_server and stop it after some timeout after inactivity (not receiving messages).

With simple process I can achieve that with this:

def MyProcess do
  def new do      
    spawn fn -> init() end
  end

  def init do 
    state = %State{}
    loop(state)
  end

  def loop(state) do 
    receive do 
      some_stuff -> 
        # some stuff going here
        loop(state)
    after
      @timeout -> 
        exit(:normal)
    end
  end
end

How to do the same with gen_server?

First 5 of 5 Posts Switch mode

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Create a timer when you start the genserver. In all of your message callbacks bump the timer. If you ever receive a message from the timer, quit.

rcavanaugh

rcavanaugh

If I’m reading this properly, there’s actually something built into GenServer for this too.

defmodule Timesout do
	@timeout 1000

	use GenServer
	require Logger

	def start_link do
		GenServer.start_link(__MODULE__, [])
	end

	def init(_) do
		Logger.info "starting up with timeout #{@timeout}"

		{:ok, [], @timeout}
	end

	def handle_call({:add, a, b}, _, _) do
		Logger.info "adding and resetting timer"

		{:reply, a + b, [], @timeout}
	end

	def handle_info(:timeout, _) do
		Logger.info "shutting down"

		{:stop, :normal, []}
	end
end

{:ok, p} = Timesout.start_link

Process.sleep(900)

IO.inspect GenServer.call(p, {:add, 10, 20})

Process.sleep(1100)

IO.inspect GenServer.call(p, {:add, 20, 50})

This results in:

> elixir timesout.exs                                                                                                                                                                                                         2646ms  Wed Sep 21 10:42:38 2016

10:43:37.778 [info]  starting up with timeout 1000

10:43:38.685 [info]  adding and resetting timer
30

10:43:39.688 [info]  shutting down
** (exit) exited in: GenServer.call(#PID<0.76.0>, {:add, 20, 50}, 5000)
    ** (EXIT) no process
    (elixir) lib/gen_server.ex:604: GenServer.call/3
    timesout.exs:38: (file)
    (elixir) lib/code.ex:363: Code.require_file/2
astery

astery OP

I was the one who read it badly, thank you it helps.

brightball

brightball

Thanks for bringing it to the board. I wasn’t aware of it and it solves a problem for me too.

silviurosu

silviurosu

Does this timeout includes messages from all call and cast methods? For example in my GenServer I have a few call methods and a few cast methods and I return
{:reply, reply, new_state, timeout}
or
{:noreply, new_state, timeout}

timeout refers to calls to any of this methods or just to that specific call or cast?
I hope my question is clear.

— All posts loaded —

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New

We're in Beta

About us Mission Statement