DynamicSupervisor

From Elixir Wiki
Jump to navigation Jump to search

DynamicSupervisor[edit]

The `DynamicSupervisor` module in Elixir is a powerful tool that allows for dynamic supervision of processes. It is a part of the `Supervisor` behavior, which is key to building fault-tolerant systems in Elixir. With the `DynamicSupervisor`, you can dynamically add and remove child processes at runtime without needing to restart the supervision tree.

Usage[edit]

To use the `DynamicSupervisor`, you first need to start a dynamic supervisor by calling `DynamicSupervisor.start_link/2` or `DynamicSupervisor.start/2`. This will create a supervisor process that will handle the dynamic addition and removal of child processes.

Once the dynamic supervisor is started, you can use the various functions available in the `DynamicSupervisor` module to manage the child processes. Some of the most commonly used functions include:

  • `DynamicSupervisor.start_child/2` to start a new child process
  • `DynamicSupervisor.terminate_child/2` to terminate a child process
  • `DynamicSupervisor.replace_child/3` to replace a child process with a new one
  • `DynamicSupervisor.update_child/3` to update the child specification of a running process

Example[edit]

Here is an example that demonstrates the usage of `DynamicSupervisor`:

```elixir defmodule MyApp.Supervisor do

 use DynamicSupervisor
 def start_link(_) do
   DynamicSupervisor.start_link(__MODULE__, nil, name: __MODULE__)
 end
 def init(nil) do
   DynamicSupervisor.init(strategy: :one_for_one)
 end

end

defmodule MyApp.Worker do

 def start_link(arg) do
   Task.start_link(fn ->
     loop(arg)
   end)
 end
 defp loop(counter) do
   IO.puts("Counter: #{counter}")
   :timer.sleep(1000)
   loop(counter + 1)
 end

end

{:ok, _} = MyApp.Supervisor.start_link(nil) {:ok, _} = DynamicSupervisor.start_child(MyApp.Supervisor, {MyApp.Worker, :start_link, [0]})

timer.sleep(5000)

DynamicSupervisor.terminate_child(MyApp.Supervisor, worker_pid) ```

In this example, we define a dynamic supervisor using the `DynamicSupervisor` module. We then start the supervisor and add a child process using `DynamicSupervisor.start_child/2`. After a delay of 5 seconds, we terminate the child process.

Benefits[edit]

The `DynamicSupervisor` provides several benefits, including:

  • Dynamically adding and removing child processes without restarting the supervision tree
  • Increased flexibility and reusability of supervision trees
  • Simplified code and improved modularity

Conclusion[edit]

The `DynamicSupervisor` module in Elixir is a powerful tool for dynamic process supervision. It allows for the dynamic addition and removal of child processes at runtime without needing to restart the supervision tree. By using the `DynamicSupervisor`, you can build fault-tolerant systems that can adapt and evolve as needed.

See Also[edit]

References[edit]

<references />