parallel_task v0.1.1 ParallelTask

Elixir library to run multiple functions in parallel and capture the results.

Suitable for multiple slow tasks such as API calls and database queries which can be performed concurrently. The process will be blocked until all functions have returned or the timeout has been reached.

Examples

Run two functions in parallel. results will be a map of keys and results.

results = ParallelTask.new
          # Add some long running tasks eg. API calls
          |> ParallelTask.add(first_task: fn -> "Result from first task" end)
          |> ParallelTask.add(second_task: fn -> "Result from second task" end)
          |> ParallelTask.perform

Use pattern matching to easily extract the results.

%{
  first_task: first_result,
  second_task
} = results

IO.puts first_result # "Result from first task"
IO.puts second_result # "Result from second task"

Link to this section Summary

Functions

Adds new functions to a parallel task. Every function is bound to a key

Creates a new parallel task

Runs a parallel task and returns a map of the results

Link to this section Functions

Link to this function add(object, new_functions \\ [])
Link to this function add(object, key, function)

Adds new functions to a parallel task. Every function is bound to a key.

ParallelTask.new |> ParallelTask.add(first: fn -> "First function", second: fn -> "Second function")

ParallelTask.new
|> ParallelTask.add(first: fn -> "First function" end)
|> ParallelTask.add(second: fn -> "Second function" end)

Creates a new parallel task

Link to this function perform(parallel_task, timeout \\ 5000)

Runs a parallel task and returns a map of the results.

The process will be blocked until all functions have returned or the timeout has been reached.

A custom timeout can optionally be passed. Functions running longer than the timeout will automatically be killed and their result will be nil. The default timeout is 5 seconds.

iex> ParallelTask.new |> ParallelTask.add(first: fn -> "Hello world" end) |> ParallelTask.perform
%{
  first: "Hello world"
}