使用时的子参数:simple_one_for_one策略

时间:2016-03-12 22:24:48

标签: elixir

使用:simple_one_for_one策略时,我们指定要动态启动的子项:

supervise([worker(FooServer, [])], strategy: :simple_one_for_one)

然后我们使用以下内容来启动孩子:

def start_child(arg1, arg2) do
  Supervisor.start_child(__MODULE__, [arg1, arg2])
end

documentation州(强调我的):

  

在:simple_one_for_one的情况下,将使用在主管中定义的子规范,而不是child_spec,期望任意的术语列表。然后,通过将给定列表附加到子规范 中的现有函数参数来启动子进程

我尝试了以下

supervise([worker(FooServer, [:foo])], strategy: :simple_one_for_one)
#                             ^^^^
#                             "fixed" argument

但似乎没有附加参数,我找不到如何访问这些固定参数。甚至可以这样做吗?

1 个答案:

答案 0 :(得分:4)

我在iex中使用了以下代码:

defmodule Child do
  def start_link(arg, arg2) do
    IO.inspect(arg)
    IO.inspect(arg2)

    pid = spawn fn() ->
      receive do
        _any -> arg
      end
    end

    {:ok, pid}
  end
end

defmodule Sup do
  use Supervisor

  def start_link do
    Supervisor.start_link(__MODULE__, [], name: __MODULE__)
  end

  def init(_args) do
    children = [
      worker(Child, [:arg], restart: :transient)
    ]

    supervise(children, strategy: :simple_one_for_one)
  end

  def start_child do
    Supervisor.start_child(__MODULE__, [:arg2])
  end
end

这是我的行为:

iex(1)> Supervisor.start_link
  {:ok, #PID<xxxxx>}
iex(2)> Supervisor.start_child
  :arg
  :arg2
  {:ok, #PID<0.69.0>}

所以看起来它对我来说是正常的。很难就代码中发生的事情提供建议而不能看到你的代码,但也许你的期望是你的论证是一个args列表,而不是你接收每个args作为单独的参数。