Quixir/Supervisors

From Elixir Wiki
Jump to navigation Jump to search

The Quixir/Supervisors page is currently empty.

Overview[edit]

In Elixir, supervisors are used to manage the lifecycle of child processes. They are responsible for starting, stopping, and restarting child processes when needed, ensuring fault tolerance and reliability in the system.

Purpose[edit]

Supervisors play a key role in building fault-tolerant systems. By organizing processes into a supervision tree, supervisors can detect when a process crashes and automatically restart it, allowing the system to recover from faults without manual intervention.

How Supervisors Work[edit]

Supervisors are defined using the `use` macro from the `Supervisor` module. They specify a set of child processes that they supervise, along with strategies for restarting those processes in case of failure.

Child Specification[edit]

Each child process is defined using a child specification, which includes the module and arguments needed to start the process.

Restart Strategies[edit]

Supervisors define restart strategies that determine how child processes should be restarted after a failure. Some common strategies include:

  • `:one_for_one`: Only restart the failed process itself.
  • `:one_for_all`: Restart all child processes.
  • `:rest_for_one`: Restart the failed process and all others that were started after it.

Supervisor Strategies[edit]

Supervisors also define their own restart strategy, which determines how the supervisor itself should be restarted. Common strategies include:

  • `:one_for_one`: Only restart the failed supervisor.
  • `:one_for_all`: Restart the failed supervisor and all other supervisors in the supervision tree.
  • `:rest_for_one`: Restart the failed supervisor and all supervisors that were started after it.

Handling Failures[edit]

When a supervised process terminates abnormally, the supervisor receives an exit signal and can take appropriate action. This could involve restarting the process, logging the error, or escalating the error to a higher-level supervisor.

Example Usage[edit]

```elixir defmodule MyApp.Supervisor do

 use Supervisor
 def start_link do
   Supervisor.start_link(__MODULE__, [])
 end
 def init([]) do
   children = [
     worker(MyApp.Worker, [])
   ]
   supervise(children, strategy: :one_for_one)
 end

end ```

Conclusion[edit]

Supervisors are a fundamental building block in creating reliable and fault-tolerant systems with Elixir. By organizing processes into a supervision tree and defining appropriate restart strategies, developers can ensure that their applications can recover from failures and provide a robust user experience.

See Also[edit]