Skip to content

Instantly share code, notes, and snippets.

@joshnuss
Last active May 10, 2019 14:05
Show Gist options
  • Save joshnuss/2091ec283938ead9e4d91570edad62b5 to your computer and use it in GitHub Desktop.
Save joshnuss/2091ec283938ead9e4d91570edad62b5 to your computer and use it in GitHub Desktop.
Module for running multiple tasks
defmodule MultiTask do
@moduledoc "Tools for running multiple tasks simultaneously"
@spec async([fun]) :: Task.t
@doc "Start multiple tasks asynchronously"
def async(tasks) do
Enum.map(tasks, &Task.async/1)
end
@spec await([Task.t]) :: [term]
@doc "Wait on multiple tasks asynchronously"
def await(tasks) do
Enum.map(tasks, &Task.await/1)
end
@spec resolve([fun]) :: [term]
@doc "Start multiple tasks and wait on them simultaneosly. Blocks the calling process."
def resolve(tasks) do
tasks
|> async()
|> await()
end
end
# Example of using this
defmodule FedEx do
def run do
Process.sleep(1000)
{:ok, :fedex}
end
end
defmodule UPS do
def run do
Process.sleep(2000)
{:ok, :ups}
end
end
defmodule USPS do
def run do
Process.sleep(2000)
{:ok, :usps}
end
end
tasks = [
&UPS.run/0,
&USPS.run/0,
&FedEx.run/0
]
MultiTask.resolve(tasks) |> IO.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment