Polling with a gen_server

Hello,

I need help finding information spawning multiple gen_servers that will poll for information. This is my current code:

  def poll_for_reply(number) when is_binary(number)do
    spawn(Context.Twilio, :poll_for_reply, [%{number: number, count: 0}])
  end

  def poll_for_reply(map) when is_map(map) do
    case inbound_messages(for: map.number) do
      [] ->
        Logger.info "No reply: " <> "#{map.count}"
        if map.count < @timeout do
          :timer.sleep(5000)
          poll_for_reply(%{map| count: map.count + 1})
        else
          Logger.info "Hit Timeout"
        end
      [message|_tail] ->
        Logger.info message.sid
        Logger.info message.body
    end
  end

This works for me currently, but I would like to make it a gen_server and then dynamically add to a supervisor in case it fails before the timeout.

So my question is:

  • How do I get a gen_server to poll like this? Do I just call GenServer.cast(:poll) where I recurse in my example?

Thanks for any help you can give.

1 Like

You should never block inside a GenServer callback.

Inside your GenServer process, call Process.send_after and then handle the value in handle_info. That way you won’t block the GenServer process but will still be able to delay the execution of your logic.

6 Likes

Thank you. I will give that a try…