Skip to content

Instantly share code, notes, and snippets.

@underhilllabs
Created November 25, 2016 16:22
Show Gist options
  • Save underhilllabs/18a8fa44e3b42b76b698d7674849106a to your computer and use it in GitHub Desktop.
Save underhilllabs/18a8fa44e3b42b76b698d7674849106a to your computer and use it in GitHub Desktop.
How to run an Elixir Process periodically, S/O answer from Jose Valim

There is a simple alternative that does not require any external dependencies:

defmodule MyApp.Periodically do
  use GenServer

  def start_link do
    GenServer.start_link(__MODULE__, %{})
  end

  def init(state) do
    schedule_work() # Schedule work to be performed at some point
    {:ok, state}
  end

  def handle_info(:work, state) do
    # Do the work you desire here
    schedule_work() # Reschedule once more
    {:noreply, state}
  end

  defp schedule_work() do
    Process.send_after(self(), :work, 2 * 60 * 60 * 1000) # In 2 hours
  end
end

Now in your supervision tree:

worker(MyApp.Periodically, [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment