I'm trying to create a periodical timer with Elixir which would take the lenght of period (milliseconds) as parameter and a function to be executed after time has elapsed. User should also have option to cancel timer. If passed function returns :cancel value, then it should also cancel timer. Here is my code:
def start_timer(period, callback_function) do
GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
timer = Process.send_after(self(), :work, period)
{:ok, %{timer: timer}}
end
def handle_info(:work, period) do
IO.puts("This should printed after every period")
# Start the timer again
timer = Process.send_after(self(), :work, period)
{:noreply, %{timer: timer}}
end
I have not yet implemented cancel-feature or the execution of parameter function as the above doesn't work yet. How I should do this? Any advise is very highly appreciated.