Last active
May 10, 2019 14:05
-
-
Save joshnuss/2091ec283938ead9e4d91570edad62b5 to your computer and use it in GitHub Desktop.
Module for running multiple tasks
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 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 |
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
# 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