denna
Send_later to Agent
I like to make use of Process.send_later to send a message to an Agent.
When I understand this tutorial right than one needs to implement handle_info to handle the message send by send_after. Agent doesn’t implement handle_info. Only gen_server does so.
As an example one could use the counter from the documentation:
defmodule Counter do
use Agent
def start_link(initial_value) do
Agent.start_link(fn -> initial_value end, name: __MODULE__)
end
def value do
Agent.get(__MODULE__, & &1)
end
def increment do
Agent.update(__MODULE__, &(&1 + 1))
end
end
Counter.start_link(1)
Process.send_after(Counter,:increment,1000)
Most Liked
hauleth
Agent is thin wrapper over GenServer, so the performance should be similar.
And your example using GenServer will not be much more complex:
defmodule Counter do
use GenServer
def start_link(initial_value) do
GenServer.start_link(__MODULE__, initial_value, name: __MODULE__)
end
def value, do: GenServer.call(__MODULE__, :get)
def increment, do: GenServer.call(__MODULE__, :inc)
@impl true
def init(value), do: {:ok, value}
@impl true
def handle_call(:inc, state), do: {:reply, :ok, state + 1}
def handle_call(:get, state), do: {:reply, state, state}
end
kokolegorille
Many don’t use Agent (and prefer GenServer), and many don’t use :timer library (and prefer Process.send_after, or similar) ![]()
This is something You might learn from experience.
hauleth
Last Post!
derek-zhou
Process.send_after/4 looks up the pid from registered name at the time of timer expiration. So Process.send_after(Crap, :hi, 1000) will always succeed. And the message will be silently dropped because there is no such process. In comparison, if you send(MyGenServer, {:delayed_hi, 1000}) and in the GenServer you handle the custom message with a Process.send_after(self(), ...) it will be safer because:
- If you mis-typed the name in the first send, the sending process will crash
- The second send to self() has no lookup and will not drop message so long as it is still alive.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









