Last active
March 28, 2019 17:38
-
-
Save thiagogsr/8953738d70240ba9e7fcc878cd564185 to your computer and use it in GitHub Desktop.
Task supervisor
This file contains hidden or 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 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 |
This file contains hidden or 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
def run_later(user_id) do | |
Task.Supervisor.async(A.TaskSupervisor, fn -> | |
run(user_id) | |
end) | |
end |
This file contains hidden or 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 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 |
This file contains hidden or 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 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