Exclusive Periodic Task in Elixir Cluster

Hello,

I want to run a task every X minutes, but I’d like to be done only once. Because of this, I chose a solution using Genserver & Timeout, like this one: https://nesteryuk.info/2017/08/13/recurring-tasks-in-elixir-solution-2.html

I added this GenServer to my application tree with the name: {:global, __MODULE__}. This way avoid this task is executed each time in each cluster. After deploying, I saw a big problem. Only one node is alive because the other ones died trying to set up the periodic task which is impossible because is already registered in the alive node.

So I was thinking to check in the init function if the name has already been registered. In this case, it could return :ignore. But I see a big problem with this approach, if the whole node died unexpectly, the task won’t be executed again until a new node goes up. Not very resilient.

So, my main question is: if is there a simple way to achieve my goals or I should go with a more complex solution like using quantum?

PD: I like the GenServer solution because I can change the interval in runtime.

Thanks for your time

This does what you were trying to do: Singleton process library

The key is to do the name registration after the process starts, and then branch on the result:

  • If the registration succeeds, act as the “master”, running the periodic tasks
  • If it fails, then act as “follower” and just monitor the master. Once the master dies, try to take its place.

I took a look to the code of the library. Very intelligent solution. Thank you :smile: