View Source ConditionalChild (Conditional Child v0.1.1)
A wrapper for starting and stopping a child process in runtime, based on periodic checks.
A common use case is to start and stop processes when feature flags are toggled, but any condition can be used.
example
Example
Suppose you have a static Demo.Worker
child in your application supervision tree:
defmodule Demo.Application do
@moduledoc false
use Application
@impl true
def start(_type, _args) do
children = [
Demo.Worker
]
opts = [strategy: :one_for_one, name: Demo.Supervisor]
Supervisor.start_link(children, opts)
end
end
To make it conditional, just wrap it in a ConditionalChild
process, passing
start_if
and child
options, like in the diff below:
- Demo.Worker
+ {ConditionalChild, child: Demo.Worker, start_if: fn -> your_condition() end}
Becoming:
defmodule Demo.Application do
@moduledoc false
use Application
@impl true
def start(_type, _args) do
children = [
{ConditionalChild, child: Demo.Worker, start_if: fn -> your_condition() end}
]
opts = [strategy: :one_for_one, name: Demo.Supervisor]
Supervisor.start_link(children, opts)
end
end
During initialization, ConditionalChild
will execute start_if
and only start the child process
if it evaluates to true
.
After that, it will execute start_if
every second, and start/stop the process based on the
result.
If every second is too much, the check interval can by changed via the interval
option, e.g.:
{
ConditionalChild,
child: Demo.Worker,
start_if: fn -> your_condition() end,
interval: :timer.seconds(5)
}
ConditionalChild
is linked to the managed child process, meaning that if the child process exits,
it will exit together with the same reason and be restarted by the parent supervisor.
Any child_spec
-compatible
value can be passed as the child
option.
Link to this section Summary
Functions
Returns a specification to start this module under a supervisor.
Link to this section Functions
Returns a specification to start this module under a supervisor.
See Supervisor
.