Using Elixir Supervisor's start_link and start_child

This gives a very simple example of using Elixir's supervisor - which setups a supervisor and ensure your application is running well .If your application stops, supervisor will automatically restart it - using one-for-one strategy.

Here we have a module called Test and further down, we have code to setup our Supervisor. The text in bold, are the name we have given to our apps.

We tell Supervisor to start our process by calling Test.say().

Our basic dummy module

defmodule Test do
   def say() do
     IO.puts "test"

This is where we do all our setup.

import Supervisor.Spec

children = [
  supervisor(Task.Supervisor, [[name: Test, restart: :transient]]),

{:ok, pid} = Supervisor.start_link(children, strategy: :one_for_one)

Runs our module.

Task.Supervisor.start_child(Test, fn -> Test.say() end)

That's it. Bottom line is, you need to setup your supervisor and then you ask Supervisor to start running a module. 


Popular posts from this blog

A quick tutorial for OWASP ZAP tool for beginners

ionic2 cordova build android - Unable resolve gradle 2.2.3