Last active
September 14, 2015 07:49
-
-
Save shankardevy/42379aae50757a666d66 to your computer and use it in GitHub Desktop.
Supervisor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule MyApp.Worker.Supervisor do | |
use Supervisor | |
def start_link do | |
Supervisor.start_link(__MODULE__, [], name: __MODULE__) | |
end | |
def init(_) do | |
Task.start_link(&MyApp.Worker.Supervisor.initiate_workers/0) | |
supervise( | |
[worker(MyApp.Worker, [], [restart: :permanent, shutdown: :infinity])], | |
strategy: :simple_one_for_one ) | |
end | |
def start_child(args) do | |
Supervisor.start_child(__MODULE__, [args]) | |
end | |
def initiate_workers do | |
Camera | |
|> MyApp.Repo.all | |
|> Enum.map(&(start_camera_worker &1)) | |
end | |
def start_camera_worker(camera_with_index) do | |
.... | |
..... | |
MyApp.Worker.Supervisor.start_child(args) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule MyApp.Worker do | |
import MyApp.Snapshot | |
import MyApp.Schedule | |
def start_link(args) do | |
worker_name = args[:camera_exid] |> String.to_atom | |
GenServer.start_link(__MODULE__, args, name: worker_name) | |
end | |
def init(args) do | |
Task.start_link(fn -> loop(args) end) | |
end | |
defp loop(args) do | |
... | |
... | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The approach would be to create a module that would be your
WorkerMonitor
(feel free to rename it to something more fitting). ThisWorkerMonitor
will be directly supervised by your Supervisor. In yourWorkerMonitor
genserver, you start the Genserver module that you will be monitoring. I think you could do it with http://elixir-lang.org/docs/master/elixir/Kernel.html#spawn_monitor/3.In your
WorkerMonitor
, define ahandle_info
callback that handles the message{:DOWN, ref, process, pid, reason}
then eitherspawn_monitor/3
the process or do nothing depending on the type of error you got.