anuaralfetahe

anuaralfetahe

Long running process with periodic tasks

Hi everyone!

I am building an app using phoenix which is holding websocket connections with other servers and receiving messages every other second. Currently I am caching all the messages I get from other servers.
Now I would need to make some calculations based on the data I am receving, atleast once in a minute.
I thought of long running process which would be supervised by another process.
Using Process.sleep(60000) I can force the process to wait for 1 minute before running the calculations again.
Is this optimal or are there any better solutions for this kind of work? Any ideas are welcome :slight_smile:

Marked As Solved

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Usually the approach is to use Process.send_after(self(), :calculate, 60_000) and then have a def handle_info(:calculate, state) do and do the calculation there.

Also Liked

cenotaph

cenotaph

Kind of need to forget what you know about normal programming limitations and welcome the recursive and process infinite loop here.

as @benwilson512 mentioned the most efficient way is to recursively call yourself after you have done your calculations.

Your calculations might run over 60seconds to complete.
The operating system scheduler might not wake your thread up at the exact time
Cron job handler might have a problem and not launch any of your jobs
These are all the limitations we introduced to programming languages when we made the mainloop invisible to consumers.

dimitarvp

dimitarvp

  • Have a GenServer that is responsible for calculating and returning the aggregated data.
  • Have that GenServer maintain this state:
    • Date/time showing when it last did a calculation.
    • Last cached calculation.
  • When the GenServer receives a message to supply the aggregated data, have it check against the date/time; if more than 60_000 ms have passed, re-calculate it and return it. If the data has been calculated less time before that, just return a cached response.

I personally wouldn’t reach for a fixed time period recalculation. Imagine if nobody pings that state for a week. Why recalculate it every minute?

It depends on the project and how frequently will this data be requested but in any case, food for thought. I have changed several hobby projects to the pattern above and my OCD about not wasting CPU resources has calmed down. :101:

amnu3387

amnu3387

The usual way is to use send_after as @benwilson512 mentioned to schedule itself. Process.sleep shouldn’t really be used outside of very niche cases (e.g., maybe helpers for retry/backoff, testing)

Different flows will depend on what you need to do in that interval. Some considerations:

  • Can the activity you plan to do every interval take more than the interval itself? What should happen if it does?
  • Does it depend on the existence of other processes (e.g. it can schedule itself)? Or can it be always running no matter what, even in the absence of relevant sources/data?
  • How does it get its data? Is the cache/data source serialising access?
  • What side effects does it create?
  • Are you running more than 1 node and if so does it impact the way it needs to run (e.g. if the side-effect is writing stats into the db, or generating a pdf - of course in this case won’t be but an example - it might be that you only want a single process amongst all instances to ever be working on that)
  • Are there any hard guarantees you need regarding the timing and execution, is it ok if it just misses something or is best effort, etc

There are also gen_statems that have direct utilities for timers and can be useful if the flow has any semblance to a list of steps (or obviously a state-machiney nature). Like, set timer → wait → timer fires → load data → do something → do something else → set timer → wait → repeat…

anuaralfetahe

anuaralfetahe

Those are very good things to consider.
The calculations should be fast but Im holding hundreds of websocket connections which are all getting messages every other second. Perhaps there should be even multiple processes for the calculations.
I am actualy amazed by the way elixir can handle processes, so spawing more processes for each work is no problem I think.

Where Next?

Popular in Questions Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
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
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
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
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
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
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
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

We're in Beta

About us Mission Statement