Advertisement
Guest User

Untitled

a guest
Oct 8th, 2015
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. defmodule EventWatcher do
  2. use Application
  3.  
  4. def start(_type, _args) do
  5. import Supervisor.Spec, warn: false
  6.  
  7. children = [
  8. worker(GenEvent, [[name: EventWatcher.GenEvent]], [id: :event_manager]),
  9. supervisor(EventWatcher.Watcher.Supervisor, [], [id: :watcher_supervisor])
  10. ]
  11.  
  12. # `:rest_for_one` will restart watchers if event manager exits
  13. opts = [strategy: :rest_for_one, name: EventWatcher.Supervisor]
  14. Supervisor.start_link(children, opts)
  15. end
  16. end
  17.  
  18. defmodule EventWatcher.Watcher.Supervisor do
  19. use Supervisor
  20.  
  21. def start_link() do
  22. Supervisor.start_link(__MODULE__, nil, [name: __MODULE__])
  23. end
  24.  
  25. def init(_) do
  26. default_handlers = [{EventWatcher.IO, :stdio}]
  27. handlers = Application.get_env(:event_watcher, :handlers, default_handlers)
  28. children = for {handler, args} <- handlers do
  29. # Watcher has `:id` matching handler so two watchers don't try to add the
  30. # same handler. `:restart` is `:transient` so a handler can remove itself
  31. # gracefully (see `:normal` stop below), other restarts can be valid too.
  32. worker(EventWatcher.Watcher, [handler, args], [id: handler, restart: :transient])
  33. end
  34. supervise(children, [strategy: :one_for_one])
  35. end
  36. end
  37.  
  38. defmodule EventWatcher.Watcher do
  39. use GenServer
  40.  
  41. def start_link(handler, args) do
  42. GenServer.start_link(__MODULE__, {handler, args})
  43. end
  44.  
  45. def init({handler, args}) do
  46. case GenEvent.add_mon_handler(EventWatcher.GenEvent, handler, args) do
  47. :ok -> {:ok, handler}
  48. {:error, :ignore} -> :ignore # special case to ignore handler
  49. {:error, reason} -> exit({:failed_to_add_handler, handler, reason})
  50. end
  51. end
  52.  
  53. def handle_info({:gen_event_EXIT, handler, reason}, handler) do
  54. {:stop, reason, handler}
  55. end
  56. end
  57.  
  58. defmodule EventWatcher.IO do
  59. use GenEvent
  60.  
  61. def handle_event(event, device) do
  62. IO.inspect(event)
  63. {:ok, device}
  64. end
  65. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement