凤凰APP上线后去哪里做任务?

Where to do tasks after the Phoenix app is launched?

背景

我正在尝试使用 Phoenix LiveView 创建桌面应用程序。现在,以某种用户友好的方式(至少我知道的唯一一种方式)执行此操作的唯一方法是启动我的 Phoenix app/server,然后在客户端计算机中打开浏览器 window。

这就是诀窍。在客户端的机器上打开浏览器 window。

代码

通过查看其他强大的 Elixir 程序员的一些 github 存储库,我能够获取一段代码,在某种程度上可以完成这项工作。

demo/lib/demo/application.ex

defmodule Demo.Application do
  @moduledoc false

  use Application

  def start(_type, _args) do
    children = [
      DemoWeb.Telemetry,
      {Phoenix.PubSub, name: Demo.PubSub},
      DemoWeb.Endpoint
    ]

    opts = [strategy: :one_for_one, name: Demo.Supervisor]
    result = Supervisor.start_link(children, opts)

    start_browser_command =
      case :os.type do
        {:win32, _} ->
          "start"
        {:unix, :darwin} ->
          "open"
        {:unix, _} ->
          "xdg-open"
      end

    if System.find_executable(start_browser_command) do
      System.cmd(start_browser_command, ["http://localhost:4000"])
    else
      Mix.raise "Command not found: #{start_browser_command}"
    end

    result
  end

  def config_change(changed, _new, removed) do
    DemoWeb.Endpoint.config_change(changed, removed)
    :ok
  end
end

这应该首先启动 Phoenix App 然后打开 window。

问题

因此,由于特定原因,这段代码让我感到有点不舒服:我的印象是 start 函数应该只用于启动我的 phoenix 服务器,而不用于其他任何东西。

但是问题来了:

通常,我们使用 Application.start_phase/3 正是为此目的而发明的。

如果您想 运行 它是异步的,只需生成另一个受监督的 GenServer 即可在完成工作后从那里优雅地实现 handle_continue/2{:stop, :normal, _}