elixir - 为什么 Supervisor.start_child 不起作用

标签 elixir erlang-otp

我是 Elixir 的初学者。

我有一个应用程序在 application.ex 中启动一个自定义主管。代码:

defmodule MyApp do
  use Application

  def start(_type, _args) do
    import Supervisor.Spec

    children = [
      supervisor(MyApp.Web.Endpoint, []),
      supervisor(MyApp.Repo, []),

      #my notifier
      MyApp.MyNotifier.Supervisor
    ]
    opts = [strategy: :one_for_one, name: MyApp.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

supervisor的代码是这样的:

defmodule MyApp.MyNotifier.Supervisor do

  use Supervisor

  def start_link(_options), do:
    Supervisor.start_link(__MODULE__, :ok, name: __MODULE__)

  def start_my_notifier(state) do
    Supervisor.start_child(__MODULE__, state)
  end

  def init(:ok) do
    Supervisor.init([], strategy: :one_for_one)
  end

end

worker 的代码是这样的:

defmodule MyApp.MyNotifier do
  use GenServer

  # Client

  def start_link(state) do
    GenServer.start_link(__MODULE__, state)
  end

  # Server

  def init(state) do
    # Reschedule
    reschedule(state)
    # Reply
    {:ok, state}
  end

  def handle_info(:reschedule, state) do

    case state["count"] < 9 do
      true ->
        # Send notification
        MyNotifier.Helper.notify_past_delivery_time(sate["id"])
        # Reschedule once more
        reschedule(state)
      false ->
        # End process
        Process.exit(self(), :normal)
    end

    {:noreply, state}
  end

  defp reschedule(state) do
    Process.send_after(self(), :reschedule, state["time"] * 60 * 1000)
  end
end

当我的应用程序中发生某些情况时,我想使用以下代码动态添加/启动一个工作人员:

MyNotifier.Supervisor.start_my_notifier(%{"name" => name, "id" => id, "time" => 15, "count" => 0})

当我在 Debug模式下运行应用程序时(iex -S mix phx.server)并将一个 IEx.pry 放入工作线程的 init 函数中(然后我们强制应用程序进入启动子进程的状态)。为什么应用程序永远不会停止?

最佳答案

调用Supervisor.start_child/2的第二个参数应该是一个子规范,所以而不是:

Supervisor.start_child(__MODULE__, state)

它应该有点像:

Supervisor.start_child(__MODULE__, [self(), MyApp.MyNotifier, [state]])

关于elixir - 为什么 Supervisor.start_child 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48705526/

相关文章:

elixir - 生成N个自然数的序列

elixir - 对于 "endless"重复任务,我应该使用哪种 OTP 行为?

Elixir Redix 基于名称的池示例 - 主管签名不存在

erlang-otp - 在线用户存储 Elixir

elixir - 如何在 GenServer 中执行对当前进程的调用?

Elixir 混合编译优先级

macros - 在引用 block 中调用私有(private)宏

elixir - 如何测试具有所需关联的模型

macros - Elixir 中的宏扩展 : how to define 2 macros with one using the other?

java - 从 Java 获取 Ping 到 Erlang