如何在长生不老药中运行无限job/process?

How to run an infinite job/process in elixir?

我正在尝试创建一个没有框架的应用程序来无限地 运行 后台作业。

我已经建立了一个空的 mix 项目,它有以下文件:

# lib/application.ex
defmodule Foo.Application do
  use Application

  @impl true
  def start(_type, _args) do
    children = [
      {Foo.Counter, []}
    ]
    Supervisor.start_link(children, strategy: :one_for_one)
  end
end
# lib/counter.ex
defmodule Foo.Counter do
  use GenServer

  @time_interval_ms 1000

  def start_link(_) do
    GenServer.start_link(__MODULE__, 0)
  end

  @impl true
  def init(counter) do
    Process.send_after(self(), :increment, @time_interval_ms)
    {:ok, counter}
  end

  @impl true
  def handle_info(:increment, counter) do
    Process.send_after(self(), :increment, @time_interval_ms)
    IO.puts(counter)
    {:noreply, counter+1}
  end
end

applications 在我的 mix.exs 中看起来如下:

def application do
    [
      mod: {Foo.Application, []},
      extra_applications: [:logger]
    ]
end

虽然,当我 运行 mix run 我什么也没得到:

$ mix run
$

然而当我 运行 iex -S mix 我可以看到计数器在后台工作:

$ iex -S mix
Erlang/OTP 24 [erts-12.1] [source] [64-bit] [smp:12:12] [ds:12:12:10] [async-threads:1] [jit]

Interactive Elixir (1.12.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> 0
1
2
3

如何让 mix run 不退出并无限地继续 运行?

如果要在命令执行完成后保留应用程序 运行,则应使用 mix run --ho-halt 而不是 mix run

All mix run options.