Skip to content

Instantly share code, notes, and snippets.

@myobie

myobie/poller.ex

Last active Apr 8, 2021
Embed
What would you like to do?
GenServer for longpoll requests with backoff in case of errors
defmodule Example.Poller do
use GenServer
@backoff [
50,
100,
150,
250,
400,
650
]
@max_backoff 1050
def start_link([notify]),
do: GenServer.start_link(__MODULE__, [notify], name: __MODULE__)
@impl true
def init([notify]) do
state = %{notify: notify, backoff_index: 0}
{:ok, state, {:continue, :request}}
end
@impl true
def handle_continue(
:request,
%{notify: notify, backoff_index: backoff_index} = state
) do
case Example.longpoll_request() do
{:ok, response} ->
send(notify, {:update, response})
{:noreply, %{state | backoff_index: 0}, {:continue, :request}}
{:error, _error} ->
timeout = Enum.at(@backoff, backoff_index, @max_backoff)
Process.send_after(self(), :retry, timeout)
{:noreply, %{state | backoff_index: backoff_index + 1}}
end
end
@impl true
def handle_info(:retry, state),
do: {:noreply, state, {:continue, :request}}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment