Elixir Task
A Task is a process that runs a single function and usually delivers one result. It is the easiest way to do work concurrently: fetch several URLs at once, resize images in parallel, run a slow computation in the background.
async and await
Task.async/1 starts the function in a new process (linked and monitored by the caller). Task.await/2 waits for its result (5 s timeout by default):
slow_square = fn n ->
Process.sleep(100)
n * n
end
{time_us, results} =
:timer.tc(fn ->
[1, 2, 3, 4, 5]
|> Enum.map(fn n -> Task.async(fn -> slow_square.(n) end) end)
|> Enum.map(&Task.await/1)
end)
IO.inspect(results)
IO.puts("took less than 300 ms: #{time_us < 300_000}")[1, 4, 9, 16, 25]
took less than 300 ms: true
Five 100 ms jobs finish in a bit more than 100 ms because they run at the same time. The results come back in the order of the tasks, not in the order they finished, because each await waits for its own task.
:timer.tc/1 is an Erlang function that returns {microseconds, result}. We print a comparison instead of the actual time, which varies.
Task.async_stream: bounded concurrency
Starting one task per item is fine for five items, but not for a million. Task.async_stream/3 processes an enumerable with at most max_concurrency tasks at a time (default: the number of CPU cores) and yields {:ok, result} for each item, in input order:
documents = [
{"intro.txt", "Welcome to the user guide"},
{"setup.txt", "Install Erlang then install Elixir"},
{"usage.txt", "Run the script"},
{"faq.txt", "Why is it called Elixir"}
]
count_words = fn {name, text} -> {name, length(String.split(text))} end
documents
|> Task.async_stream(count_words, max_concurrency: 2)
|> Enum.each(fn {:ok, {name, words}} -> IO.puts("#{name}: #{words} words") end)intro.txt: 5 words
setup.txt: 5 words
usage.txt: 3 words
faq.txt: 5 words
Options worth knowing: timeout: per item, ordered: false to receive results as they finish, and on_timeout: :kill_task to turn timeouts into {:exit, :timeout} items instead of crashing the caller.
Waiting with a timeout: Task.yield
Task.await/2 exits the caller on timeout. Task.yield/2 instead returns nil and lets you decide what to do, often combined with Task.shutdown/2:
fast = Task.async(fn -> :quick_answer end)
slow = Task.async(fn -> Process.sleep(1_000); :late_answer end)
IO.inspect(Task.yield(fast, 500))
case Task.yield(slow, 100) || Task.shutdown(slow) do
{:ok, value} -> IO.inspect(value)
nil -> IO.puts("slow task gave up after 100 ms")
end{:ok, :quick_answer}
slow task gave up after 100 ms
Task.shutdown/2 stops the task and returns its result if it happened to finish meanwhile, otherwise nil.
Waiting for many tasks: Task.await_many
tasks =
for city <- ["Lima", "Hanoi", "Accra"] do
Task.async(fn -> "#{city}: #{String.length(city)} letters" end)
end
tasks
|> Task.await_many()
|> Enum.each(&IO.puts/1)Lima: 4 letters
Hanoi: 5 letters
Accra: 5 letters
Fire-and-forget and supervised tasks
Task.start/1runs a function you don't need a result from (sending an email, writing a log). It is not linked to the caller.- In applications, prefer
Task.Supervisor:Task.Supervisor.async_nolink/2runs a task under a supervisor, so a crashing task doesn't take the caller down, andTask.Supervisor.start_child/2replacesTask.start/1.
children = [{Task.Supervisor, name: MyApp.TaskSupervisor}]
Supervisor.start_link(children, strategy: :one_for_one)
task = Task.Supervisor.async_nolink(MyApp.TaskSupervisor, fn -> risky_work() end)
case Task.yield(task, 5_000) || Task.shutdown(task) do
{:ok, result} -> result
{:exit, reason} -> {:error, reason}
nil -> {:error, :timeout}
endTask, Agent or GenServer?
| Need | Use |
|---|---|
| Run a function concurrently, get one result | Task |
| Process a collection concurrently | Task.async_stream/3 |
| Hold shared state with simple get/update | Agent |
| Long-lived process with its own protocol, timers or several message types | GenServer |
Note:
Task.asynclinks the task to the caller. If the task crashes, the caller crashes too. That's usually right: the caller asked for the result and can't continue without it.
Test yourself
In what order does Enum.map(tasks, &Task.await/1) return results?
- The order in which tasks finish
- The order of the tasks in the list
- Random order
- Sorted order
What does Task.yield(task, 100) return if the task isn't done after 100 ms?
- It raises
nil{:error, :timeout}:pending
What does Task.async_stream/3 limit with max_concurrency?
- The number of items
- The number of tasks running at the same time
- The total time
- Memory usage