O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Tasks

An Elixir task is a function that runs in the background.

tasks/tasks1.exs
 
defmodule​ Fib ​do
 
def​ of(0), ​do​: 0
 
def​ of(1), ​do​: 1
 
def​ of(n), ​do​: Fib.of(n-1) + Fib.of(n-2)
 
end
 
 
IO.puts ​"Start the task"
 
worker = Task.async(​fn​ -> Fib.of(20) ​end​)
 
IO.puts ​"Do something else"
 
# ...
 
IO.puts ​"Wait for the task"
 
result = Task.await(worker)
 
 
IO.puts ​"The result is #{result}"

The call to Task.async creates a separate process that runs the given function. The return value of async is a task descriptor (actually a PID and a ref) that we’ll use to identify the task later.

Once the task is running, the code continues with other work. When it wants to get the function’s value, it calls Task.await, passing in ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required