Hi
I’m looking for a best way to autostart a worker process.
I have my main module autogenerated as a part of supervised app: MyApp.Application
registered as MyApp.Supervisor
and then I’m adding a DynamicSupervisor
as it’s child:
defmodule MyApp.Application do
@moduledoc false
use Application
@impl true
def start(_type, _args) do
children = [
{
DynamicSupervisor,
strategy: :one_for_one,
name: MyApp.DynamicSupervisor
}
]
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
end
I also have a box standard worker that requires a single string arg:
defmodule MyApp.Worker do
use GenServer
def start_link(symbol) do
GenServer.start_link(__MODULE__, symbol, name: :"#{__MODULE__}-#{symbol}")
end
def init(symbol) do
Logger.info("Starting worker #{symbol}")
{:ok, symbol}
end
end
Question is - let’s say that I have a table in database that lists all symbols that I need to autostart - I need to start many worker processes on start of the application. Currently I added another module/process that is a child of the MyApp.Application
that on init -> handle_continue queries the database and starts workers:
def start_worker(symbol) do
DynamicSupervisor.start_child(
MyApp.DynamicSupervisor,
{MyApp.Worker, symbol}
)
end
Is this the only/best way to do it? How would you approach this problem?
Thanks in advance