How can I schedule code to run every few hours in Elixir or Phoenix framework?

Quantum lets you create, find and delete jobs at runtime.

Furthermore, you can pass arguments to the task function when creating a cronjob, and even modify the timezone if you're not happy with UTC.

If your app is running as multiple isolated instances (e.g. Heroku), there are job processors backed by PostgreSQL or Redis, that also support task scheduling:

Oban: https://github.com/sorentwo/oban

Exq: https://github.com/akira/exq

Toniq: https://github.com/joakimk/toniq

Verk: https://github.com/edgurgel/verk


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

defmodule MyApp.Periodically do
  use GenServer

  def start_link(_opts) 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:

children = [
  MyApp.Periodically
]

Supervisor.start_link(children, strategy: :one_for_one)