fireproofsocks

fireproofsocks

How to run function on startup that blocks execution?

Sometimes I need to do some quick setup tasks before my app starts. There is a similar question here:

However, the problem is that using a Task for this does not block execution.

In other words, if I have something like this:

    children = [
      {Task,
       fn ->
          Foo.setup_stuff()
       end},
      {Foo.Worker, 100}
    ]

There appears to be no guarantee that the Task runs before the other children.

For a quick solution, I could simply rearrange my app’s start/2 so it does something like this:

    Foo.setup_stuff()
    children = [
      {Foo.Worker, 100}
    ]

    opts = [strategy: :one_for_one, name: Foo.Supervisor]
    Supervisor.start_link(children, opts)

Is there a better or more idiomatic way to do this?

Most Liked

andyleclair

andyleclair

Your solution of calling the function before passing the children to Supervisor.start_link is totally reasonable, and is what Sentry does to set up its’ Logger backend. However, you’ll need to make sure that whatever lib you’re using to make the HTTP request is started before you make the call! Req might do this for you automatically (guessing yes) but I know Finch won’t, as it must be started by the client app.

anthonator

anthonator

There are two main approaches to this. One is to do whatever you need to do in the application start/2 callback which you’ve already discussed. This is good if you need to do something before any process has started.

If you need some parts of the application to be started (e.g. Ecto) then you’ll need to add a process to your supervisor that performs the setup after the needed processes are started but before the processes that require the setup step.

I use the latter approach to ensure all Ecto connections have been established before moving on to starting something like Oban. What I’ve done is created a transient GenServer that performs the blocking work in the init/1 callback. This will halt the supervisor start process until the work in init/1 has finished. Once the work in init/1 has finished I return :ignore to prevent the GenServer from starting and continue on with starting the remaining processes.

Whether this is a code smell or not I’ll let you decide.

Here is some example code.

defmodule MyStartupProcess do
  use GenServer, restart: :transient

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

  @impl true
  def init(_) do
    :ok = do_setup()

    :ignore
  end
end
martosaur

martosaur

I think this should work, as you can return :ignore right from the start MFA:

defmodule OnStartup
    def child_spec(_) do
      %{id: __MODULE__, start: {__MODULE__, :startup, []}}
    end

    def startup() do
      do_something
      :ignore
    end
end

And then just add OnStartup to the list of children in your application.ex depending on when you want it to run

axelson

axelson

Scenic Core Team

You wouldn’t want to use handle_continue in this case because handle_continue will explicitly not block startup, although in my experience most of the time you actually don’t want to block startup. But this thread is specifically about the times that you do want to block startup.

Where Next?

Popular in Questions Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

We're in Beta

About us Mission Statement