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
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.
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.
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}".
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.