Yevhen Yevsyuhov
Yevhen Yevsyuhov

Reputation: 85

How to run an infinite job/process in elixir?

I'm trying to create an application without frameworks to run a background job infinitely.

I have set up an empty mix project and it has following files:

# 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 in my mix.exs looks as follows:

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

Though, when I run mix run I don't get anything:

$ mix run
$

Yet when I run iex -S mix I can see that counter is working on the background:

$ 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

How can I make so that mix run does not exit and continues to run infinitely?

Upvotes: 0

Views: 483

Answers (1)

Yevhen Yevsyuhov
Yevhen Yevsyuhov

Reputation: 85

You should use mix run --ho-halt instead of mix run if you want to keep the application running after the command finishes execution.

All mix run options.

Upvotes: 2

Related Questions