Task (Elixir)

From Elixir Wiki
Jump to navigation Jump to search

Task (Elixir)[edit]

Task in Elixir is a module that allows developers to work with concurrent programming and asynchronous execution. It provides a high-level interface for managing concurrent computations and enables efficient utilization of system resources.

Creating a Task[edit]

In order to create a task, the `Task.async/1` function is used. It takes a single argument, a function or a module and function tuple, that represents the task to be executed.

 task = Task.async(fn -> some_function() end)
 

The `Task.async/1` function returns a struct representing the task, which can be used later for tracking or interacting with the task.

Starting a Task[edit]

To start a task and execute it concurrently, the `Task.start/1` or `Task.await/1` function can be used. The `Task.start/1` function takes a task struct and starts its execution in a separate process.

 task_pid = Task.start(task)
 

The `task_pid` is the process identifier (PID) of the newly created process that executes the task.

The `Task.await/1` function can be used to wait for and get the result of a task's execution.

 task_result = Task.await(task)
 

Task Cancellation[edit]

Tasks can be cancelled using the `Task.cancel/1` or `Task.shutdown/1` function.

 Task.cancel(task)
 
 Task.shutdown(task)
 

The `Task.cancel/1` function cancels a task by sending a cancellation signal to the executing process. The `Task.shutdown/1` function, on the other hand, cancels a task and waits for its termination.

Task Supervision[edit]

Tasks can be supervised using the `Task.Supervisor` module. It provides functionality for creating and managing supervised tasks. Supervised tasks are automatically restarted in case of failure, ensuring fault-tolerance.

 supervisor = Task.Supervisor.start_link()
 task_spec = {Task, :async, [fn -> some_function() end]}
 task_ref = Task.Supervisor.async_nolink(supervisor, task_spec)
 

The `Task.Supervisor.async_nolink/2` function is used to create and start a supervised task without linking it to the supervisor process.

Task Monitoring[edit]

Tasks can be monitored using the `Task.monitor/1` function. It allows developers to receive notifications about task termination or abnormal termination.

 task_ref = Task.monitor(task)
 

The `Task.monitor/1` function returns a reference to the monitoring process, which can be used to receive notifications.

Summary[edit]

Task module in Elixir enables concurrent programming and asynchronous execution. Developers can create, start, monitor, and cancel tasks for efficient utilization of system resources. By leveraging task supervision, fault-tolerant systems can be built.

For more details on Task module, check the official Elixir documentation [1].