Skip to content

Instantly share code, notes, and snippets.

@thiagogsr
Last active March 28, 2019 17:38
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 thiagogsr/8953738d70240ba9e7fcc878cd564185 to your computer and use it in GitHub Desktop.
Save thiagogsr/8953738d70240ba9e7fcc878cd564185 to your computer and use it in GitHub Desktop.
Task supervisor
defmodule A.Application do
@moduledoc """
Application GenServer. It starts all supervisors and workers.
"""
use Application
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
import Supervisor.Spec
# Define workers and child supervisors to be supervised
children = [
# Start the Ecto repository
supervisor(A.Repo, []),
# Start your own worker by calling:
# A.Worker.start_link(arg1, arg2, arg3)
# worker(A.Worker, [arg1, arg2, arg3]),
# Start the Task supervisor
supervisor(Task.Supervisor, [[name: A.TaskSupervisor, restart: :transient]]),
supervisor(Registry, [:unique, A.Registry]),
worker(A.EssayService.Adapters.HTTP, [%{}])
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: A.Supervisor]
Supervisor.start_link(children, opts)
end
end
def run_later(user_id) do
Task.Supervisor.async(A.TaskSupervisor, fn ->
run(user_id)
end)
end
defmodule A.TaskSupervisorHelper do
@moduledoc """
Wait async tasks in a supervision tree
"""
use ExUnit.CaseTemplate
def wait_tasks_on_exit!(_context \\ %{}) do
on_exit(&wait_tasks/0)
end
def wait_tasks do
A.TaskSupervisor
|> Task.Supervisor.children()
|> Stream.each(fn pid ->
ref = Process.monitor(pid)
assert_receive {:DOWN, ^ref, :process, ^pid, _}, 5000
end)
|> Stream.run()
end
end
defmodule A.Test do
use A.DataCase, async: false
import A.TaskSupervisorHelper
setup :wait_tasks_on_exit!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment