Convenience functions for defining a supervision specification.
Example
By using the functions in this module one can define a supervisor
and start it with Supervisor.start_link/2
:
import Supervisor.Spec
children = [
worker(MyWorker, [arg1, arg2, arg3]),
supervisor(MySupervisor, [arg1])
]
Supervisor.start_link(children, strategy: :one_for_one)
In many situations, it may be handy to define supervisors backed by a module:
defmodule MySupervisor do
use Supervisor
def start_link(arg) do
Supervisor.start_link(__MODULE__, arg)
end
def init(arg) do
children = [
worker(MyWorker, [arg], restart: :temporary)
]
supervise(children, strategy: :simple_one_for_one)
end
end
Notice in this case we don't have to explicitly import
Supervisor.Spec
as use Supervisor
automatically does so.
Explicit supervisors as above are required when there is a need to:
Partialy change the supervision tree during hot-code swaps.
Define supervisors inside other supervisors.
Perform actions inside the supervision
init/1
callback.For example, you may want to start an ETS table that is linked to the supervisor (i.e. if the supervision tree needs to be restarted, the ETS table must be restarted too).
Supervisor and worker options
In the example above, we have defined workers and supervisors and each accepts the following options:
:id
- a name used to identify the child specification internally by the supervisor; defaults to the given module name:function
- the function to invoke on the child to start it:restart
- defines when the child process should restart:shutdown
- defines how a child process should be terminated:modules
- it should be a list with one element[module]
, where module is the name of the callback module only if the child process is aSupervisor
orGenServer
; if the child process is aGenEvent
, modules should be:dynamic
Restart values
The following restart values are supported:
:permanent
- the child process is always restarted:temporary
- the child process is never restarted (not even when the supervisor's strategy is:rest_for_one
or:one_for_all
):transient
- the child process is restarted only if it terminates abnormally, i.e. with another exit reason than:normal
,:shutdown
or{:shutdown, term}
Shutdown values
The following shutdown values are supported:
:brutal_kill
- the child process is unconditionally terminated usingexit(child, :kill)
.:infinity
- if the child process is a supervisor, it is a mechanism to give the subtree enough time to shutdown. It can also be used with workers with care.Finally, it can also be any integer meaning that the supervisor tells the child process to terminate by calling
Process.exit(child, :shutdown)
and then waits for an exit signal back. If no exit signal is received within the specified time (in miliseconds), the child process is unconditionally terminated usingProcess.exit(child, :kill)
.