为什么Supervisor.start_child不起作用 [英] Why Supervisor.start_child dont work

查看:105
本文介绍了为什么Supervisor.start_child不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Elixir的初学者。

I'm beginner in Elixir.

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

I have one application that initiate one custom supervisor in application.ex. Code:

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

主管的代码是像这样的东西:

And the code of supervisor is something like this:

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

工作程序的代码如下:

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

当我的应用程序发生问题时,我想使用以下代码动态地添加/启动一个worker:

And when something happens in my application i want add/start dynamically one worker with the follow code:

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

当我在调试模式下运行应用程序时(iex- S混合phx.server)并将一个IEx.pry放入worker的init函数中(然后我们迫使应用程序进入启动子进程的状态)。为什么应用程序永不停止?

When I run my application in debug mode (iex -S mix phx.server) and put one IEx.pry in init function of the worker (then we force the application to go to the state starting the child). Why application never stops?

推荐答案

我在主管代码中更改了simple_one_for_one的主管策略。

I changed the supervisor strategy for simple_one_for_one in supervisor code.

Supervisor.init([], strategy: :simple_one_for_one)

这对我有用。

这篇关于为什么Supervisor.start_child不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆