Search⌘ K
AI Features

An Introduction to the Task Module

Explore Elixir's Task module to understand how it simplifies running concurrent processes, managing results, and handling failures. Learn to process data lists, link processes, and use supervisors to build fault-tolerant concurrent applications on the Erlang VM.

Set up the tools

In this course, we cover the most popular tools for performing concurrent work using Elixir. We’ll learn about the pros and cons of each one and see how they work in practice. Like the Task module and GenServer, some of them come with Elixir. Other tools like GenStage, Flow, and Broadway are available as stand-alone libraries in the Hex.pm package registry. Knowing how to utilize each of these tools will help us leverage concurrency effectively. It will solve even the most challenging problems. Along the way, we’ll also learn to build fault-tolerant applications, recover from failures, use back-pressure to deal with limited system resources, and many more useful techniques.

Task module

To run code concurrently in Elixir, we have to start a process and execute our code within that process. We may also need to retrieve the result and use it for something else. Elixir provides a low-level function and a macro for spawn/1 and receive. However, using them could be tricky in practice, and we’ll most likely end up with a lot of repetitive code.

Elixir also ships with a module called Task, which significantly simplifies starting concurrent processes. It provides an abstraction to run code concurrently, retrieve results, handle errors, and start a series of processes. It packs many features and has a concise API, so there is rarely (if ever) a need to use the more primitive spawn/1 and receive.

In this chapter, we’ll cover everything that the Task module has to offer:

  • We’ll learn to start tasks and different ways to retrieve results.

  • We’ll tackle processing large lists of data.

  • We’ll discuss handling failure and explain how the process linking works in Elixir.

  • We’ll then learn to use one of the built-in supervisor modules for isolating process crashes.

  • Finally, we’ll discuss Elixir’s approach to error handling.

Elixir processes

Processes in Elixir are Erlang processes since Elixir runs on the Erlang Virtual Machine. Unlike operating system processes, they are very lightweight in memory usage and quick to start. The Erlang VM knows how to run them concurrently and in parallel when a multi-core CPU is present. As a result, we get concurrency and parallelism for free by using processes.