Skip to content

Instantly share code, notes, and snippets.

@shankardevy
Last active September 14, 2015 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shankardevy/42379aae50757a666d66 to your computer and use it in GitHub Desktop.
Save shankardevy/42379aae50757a666d66 to your computer and use it in GitHub Desktop.
Supervisor
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
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
@gjaldon
Copy link

gjaldon commented Sep 14, 2015

The approach would be to create a module that would be your WorkerMonitor (feel free to rename it to something more fitting). This WorkerMonitor will be directly supervised by your Supervisor. In your WorkerMonitor 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 a handle_info callback that handles the message {:DOWN, ref, process, pid, reason} then either spawn_monitor/3 the process or do nothing depending on the type of error you got.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment