How to create an event emitter using elixir, otp

What is the best way in the elixir to create a foreground process that will be marked for every given time period?

My main problem is that an approach like:

defmoulde Ticker do def tick do do_something() :timer.sleep(1000) tick end end 

works, but wrong in design. This is definitely not ticking every second, but every second PLUS time for do_something () to complete. I could spawn a “something” processing process, but there is still a slight lag.

In addition, I am trying to create a mixing application, there are some involved GenServers and the main foreground process (the one I ask here) that should call the servers every x seconds. Is there an otp way to do this?

+8
elixir eventemitter otp
source share
1 answer

I think timer:apply_interval/4 should suit your needs. It is used like this:

 defmodule Tick do def tick do IO.inspect(:tick) end end :timer.apply_interval(:timer.seconds(1), Tick, :tick, []) 

Arguments in order are the interval, module name, call function, and arguments to call. You can then send messages to GenServers inside this function. Check out the full documentation here: apply_interval / 4

Another thing to keep in mind is that if your tick function sends simple messages only to some GenServers , then it is probably very fast, so your implementation may be fine after it is wrapped in Task and connected to the control tree (unless you care about potential weak drift).

+13
source share

All Articles