Today I Learned

hashrocket A Hashrocket project

Periodic messages in Elixir

Today I needed to implement a task that happens once every 24 hours. I immediately thought, well this should be a cron job, but my co-worker suggested using the send_after method in a GenServer instead.

    Process.send_after(self, {:"$gen_cast", :get_data}, interval)

The third argument is a milliseconds argument that determines when the call will be processed. The $gen_cast is a hackish type of thing to get the GenServer to handle the call with handle_cast.

The periodism should start in the init and whenever handle_cast is called, it should schedule a new time that the message will be sent.

  def init(state) do
    work
    Process.send_after(self, {:"$gen_cast", :get_data}, interval)
    {:ok, state}
  end

  def handle_cast(:get_data, state) do
    Process.send_after(self, {:"$gen_cast", :get_data}, interval)
    work
    {:noreply, state}
  end

H/T Micah Cooper

See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.