Yugandhar Chaudhari
Yugandhar Chaudhari

Reputation: 3984

Application not restarting after normal exit

I am trying to connect to mqtt using tortoise. When my connection drops it connects on the with no problem but when my application exits it is not getting restarted according to :one_to_one strategy. I started application in mod of mix.exs. Shall I put it in supervisor and start the supervisor? It demands for start with no arguments what is the right way to achieve this. What if my application crashes? And is my connection.ex must be genserver? Please suggest.

mix.exs

defmodule SslMqtt.MixProject do
  use Mix.Project

  def project do
    [
      app: :ssl_mqtt,
      version: "0.1.0",
      elixir: "~> 1.6",
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  # Run "mix help compile.app" to learn about applications.
  def application do
    [
     mod: {SslMqtt.Application,[]}, 
     extra_applications: [:logger]
    ]
  end

  # Run "mix help deps" to learn about dependencies.
  defp deps do
    [
    {:tortoise, "~> 0.9"}
      # {:dep_from_hexpm, "~> 0.3.0"},
      # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"},
    ]
  end
end

application.ex

defmodule SslMqtt.Application do
  use Application

  def start(_type, _args) do

    IO.puts "inside supervisor application start"
    SslMqtt.Supervisor.start_link(name: SslMqtt.Supervisor)
  end
end

supervisor.ex

defmodule SslMqtt.Supervisor do
  use Supervisor

  def start_link(opts) do
    IO.puts "inside supervisor start link"
    Supervisor.start_link(__MODULE__, :ok, opts)
  end

  def init(:ok) do

    IO.puts "inside supervisor init"
    children = [

  %{
        id: SslMqtt.MqttConnection,
        start: { SslMqtt.MqttConnection, :start_link, [1,2]},
        type: :worker,
        restart: :permanent,
        shutdown: 500
      }

    ]

    Supervisor.init(children, strategy: :one_for_one)
  end
end

connection.ex

defmodule SslMqtt.MqttConnection do

def start_link(_type,_arg) do

{:ok,pid}=Tortoise.Connection.start_link(
    client_id: William,
    server: {Tortoise.Transport.Tcp, host: 'iot.eclipse.org', port: 1883},
    handler: {Tortoise.Handler.Logger, []},
    will: %Tortoise.Package.Publish{topic: "foo/bar", payload: "goodbye"}
  )
end



end

Upvotes: 0

Views: 262

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

The issue is with your Application. It should be

def start(_type, _args) do
  children = [
    {SslMqtt.Supervisor, []}
  ]

  opts = [strategy: :one_for_one, name: SslMqtt.Supervisor]
  Supervisor.start_link(children, opts)
end

That way the application would supervise SslMqtt.Supervisor. What you are doing now, you just start SslMqtt.Supervisor, unsupervised.

Upvotes: 3

Related Questions