Where to put the service / initialization code in the Elixir / Mix / Phoenix app?

I have an Elixir / Mix application (also Phoenix, but there are many non-Phoenix too), and I’m wondering what is the best way to use the β€œlaunch” code, for example, to dynamically add children to executives shooting β€œI'm alive!” pings or other things that you want to perform immediately after launch.

One obvious place is the file Application, but the expected return is the return from Supervisor.start_link(children, opts). So, for example, in a Phoenix application, I could do this:

defmodule MyApp do
  use Application

  def start(_type, _args) do
    import Supervisor.Spec

    children = [
      supervisor(MyApp.Repo, []),
      supervisor(MyApp.Endpoint, []),
      supervisor(MyApp.DynamicSupervisorThingy, [])
    ]
    opts = [strategy: :one_for_one, name: MyApp.Supervisor]
    start_val = Supervisor.start_link(children, opts)



    # --- Put things right here that I want to start ----
    MyApp.DynamicSupervisorThingy.add_children_dynamically()
    MyApp.SomeModule.do_some_thingy()
    MyApp.OtherModule.send_some_pings()
    if MIX_ENV == :prod do
      MyApp.YetAnother.prod_stuff_i_dont_want_in_dev()
    end


    start_val
  end
end

This seems wrong, but I cannot figure out where I should put this code.

+6
source share
1 answer

. Phoenix - OTP, , . Application.start {:ok, pid}, .

, - , " " , , - - - , - init, .

Application.start , : -)

+1

Source: https://habr.com/ru/post/1016472/


All Articles