Run function on startup

Simple question I could not find an answer for…

I want to perform a HTTP request once at startup of my app and log the output. Phoenix app in my case but the question is general really. I don’t need a whole genserver and all, just a function to run… somewhere

Where do I put this code?

Add one of task in your supervisor children list. You can use Task.child_spec/1 for that. This is what I am using for such jobs like Slack notifications or systemd notifications.

5 Likes

You can also use the :ignore return value in a GenServer init callback in your supervision tree, that will run your init callback and then kill/ignore the process after it’s run.

1 Like

I strongly disrecommend using GenServer with ignore for a one-off, linear sequence of events. The semantic idea of ignore, is that "you’re starting a stateful system that checks in and decides it doesn’t need to exist, which is not an error so you can’t use {:stop, reason}".

You could just as easily return {:stop, reason} if you run into an error or :ignore, but maybe I’m not following exactly what you’re getting at?

In such case I would prefer to use proc_lib directly.

defmodule Foo do 

  def go do
    GenServer.start_link(__MODULE__, :ok)
  end

  def init(_) do
    :ignore
  end

end

defmodule Bar do 

  def go do
    GenServer.start_link(__MODULE__, :ok)
  end

  def init(_) do
    {:stop, :reason}
  end

end

defmodule Baz do 

  def go do
    GenServer.start_link(__MODULE__, :ok)
  end

  def init(_) do
    {:stop, :normal}
  end

end

defmodule Quux do

  def go do
    Task.start_link(fn -> :do_something end)
  end

end

try them all in the console to get a feel of what the supervisors see.