vshesh

vshesh

"sample" an agent every second?

I have a situation where I have a pubsub, and a process receiving events from that pubsub.
I want the receiving process to update some state. That’s pretty easy with a genserver or an agent.
Then, I want another process to “sample” the process with state every second and do something.

What is the best way to accomplish this? Agent + Task?

Does that change if I want to modify the schedule at which the sampling is happening over time? (so the sampler can receive an event that changes the frequency of sampling?)

In Rx I would use a behavior and sample it with rx.sample - anything like that here welcome.

And what is the best way to expose this to the rest of my app? Should I make a mini-supervisor tree with both of these processes since they’re linked (if the receiving process goes down, no sense having the sampling process). How do I make it possible for the supervision tree to treat both of these processess together as a “single process” that can be shut down together?

Marked As Solved

ityonemo

ityonemo

I have a feeling process.send_after has some corner cases where you don’t want to use it for periodic events, since it doesn’t automatically cancel a previous firing cycle. If you’re not careful with your code you can wind up with 2x firings, 3x firings, 4x firings and so forth.

You can store the reference to your timer when you use send_interval, and that will allow you to make adjustments later, using :timer.cancel and storing a new timer ref when you rebuild the interval.

Also Liked

kokolegorille

kokolegorille

Simply pass the rate frequency as part of the server state. So You can modify it.

There is also Process.send_after.

There is an example in this tetris in Erlang, where the game loop accelarate over time.

http://www1.erlang.org/examples/small_examples/tetris.erl

kokolegorille

kokolegorille

It is also the case for Process.send_after, it returns a ref. And it is possible to read the elapsed time with Process.read_timer(ref), or cancel timer. I also store the ref in the server state.

Both are doing the same, but not the same way. I don’t use :timer module because it can get overloaded.

From Erlang -- Common Caveats

Creating timers using erlang:send_after/3 and erlang:start_timer/3, is much more efficient than using the timers provided by the timer module in STDLIB.

thoughtarray

thoughtarray

Hey all and future search engine visitors (like me). I wanted to mention something I feel was missed here. In case it matters to your program, you can ensure that your initial :tick message is sent after GenServer’s event loop is started by using the handle_continue/2 callback.

@impl true
def init(state) do
  {:ok, state, {:continue, :init}}
end

@impl true
def handle_continue(:init, state) do
  send(self(), :tick)
  {:noreply, state}
end
ityonemo

ityonemo

You probably want a more complex scheduler for this. Eg. Oban or Quantum.

If you don’t want something so heavyweight, you can just create a sampling genserver and in the init use :timer.send_interval/2 Erlang -- timer

How do I make it possible for the supervision tree to treat both of these processess together as a “single process” that can be shut down together?

change the strategy from :one_for_one to :one_for_all. Or maybe :rest_for_all.

derek-zhou

derek-zhou

Just send yourself a message using send_after then from the handler broadcast your state:

 def init(_) do
    # compute init state
    Process.send_after(self(), :tick, 1000)
    {:ok, state}
  end

def handle_info(:tick, state) do
    Phoenix.PubSub.broadcast(My.PubSub, "sample", {:sample, state})
    Process.send_after(self(), :tick, 1000)
end

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
Kagamiiiii
Student & New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New

Other popular topics Top

yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement