Foo42
Foo42

Reputation: 3144

Elixir supervisor is restarting a temporary/transient worker unexpectedly

I want to supervise a task with using a :transient restart policy such that it is only restarted if it exits abnormally. However when I tested my application I found it restarting it 4 times, before the supervisor bailed out itself. I simplified the code, and even changed the restart to :temporary but even then the supervisor is restarting the task.

Simplified example:

defmodule FooSup do
  use Supervisor

  def start_link() do
    IO.puts "starting #{__MODULE__}"
    Supervisor.start_link(__MODULE__, {})
  end

  def init(_)do
    children = [worker(Task, [fn -> IO.puts("task running") end])]
    supervise(children, strategy: :one_for_one, restart: :temporary)
  end
end 

When I start the FooSup process I get the following output:

iex(2)> FooSup.start_link()
starting Elixir.FooSup
task running
{:ok, #PID<0.215.0>}
task running
task running
task running

Incidentally, I know that if I want dynamically supervised :temporary tasks I can use the TaskSupervisor, but I want statically supervised with :transient really.

Been using Elixir on and off for a few years but can't see what's wrong here.

Upvotes: 0

Views: 932

Answers (1)

Paweł Dawczak
Paweł Dawczak

Reputation: 9639

I've just checked locally, and the restart should be an option to worker instead of supervise, so it should look like:

defmodule FooSup do
  use Supervisor

  def start_link() do
    IO.puts "starting #{__MODULE__}"
    Supervisor.start_link(__MODULE__, {})
  end

  def init(_)do
    children = [worker(Task, [fn -> IO.puts("task running") end], restart: :temporary)]
    supervise(children, strategy: :one_for_one)
  end
end 

More can be found here: https://hexdocs.pm/elixir/Supervisor.html#module-simple-one-for-one

Good luck!

Upvotes: 3

Related Questions