ExUtils.Runner (ExUtils v1.0.1)

Copy Markdown View Source

Utilities for running isolated tasks with various approaches.

You can run tasks in the background, add delays, or run many in parallel.

For these to work, it requires you to include ExUtils.Runner in your application supervision tree:

# in application.ex, add `ExUtils.Runner` under children
children = [
  ExUtils.Runner,
  YourApp.Repo,
  # ...
]

Summary

Functions

Runs a function in a supervised background task, returning its pid.

Groups a list of {:ok, ...} and {:error, ...} results into a map.

Runs multiple tasks concurrently.

Runs multiple tasks concurrently.

Types

background_opt()

@type background_opt() :: {:delay, non_neg_integer()}

parallel_opt()

@type parallel_opt() ::
  {:concurrency, pos_integer()}
  | {:timeout, timeout()}
  | {:on_timeout, :exit | :kill_task}

Functions

background(opts \\ [], fun)

@spec background([background_opt()], (-> any())) ::
  {:ok, nil | pid()} | {:error, term()}

Runs a function in a supervised background task, returning its pid.

When the configured application's :testing? value is true, the function runs synchronously and nil is returned instead of the pid.

Options

  • :delay - the number of milliseconds to wait before running the function.

Example

iex> ExUtils.Runner.background(fn -> :done end)
{:ok, #PID<0.100.3>}

group_results(list)

@spec group_results([{:ok | :error, any()}]) :: %{ok: [any()], error: [any()]}

Groups a list of {:ok, ...} and {:error, ...} results into a map.

Useful for grouping results from operations that return tagged tuples.

Example

iex> ExUtils.Runner.group_results([ok: 1, error: :unavailable, ok: 2])
%{ok: [1, 2], error: [:unavailable]}

parallel(list, opts \\ [], fun)

@spec parallel(Enumerable.t(), [parallel_opt()], (any() -> any())) :: [
  ok: any(),
  exit: any()
]

Runs multiple tasks concurrently.

parallel!/3 is the better fit in most cases since this function returns the raw process response after execution; returning an :ok tuple when the function executes without exceptions, and an :exit tuple otherwise.

Options

  • :concurrency - the maximum number of tasks to run concurrently. Defaults to 5.
  • :timeout - the maximum time in milliseconds each task may run. Defaults to 10_000.
  • :on_timeout - either :exit or :kill_task.

Example

iex> ExUtils.Runner.parallel([1, 2, 3], fn number -> number * 2 end)
[ok: 2, ok: 4, ok: 6]

parallel!(list, opts \\ [], fun)

@spec parallel!(Enumerable.t(), [parallel_opt()], (any() -> any())) :: [any()]

Runs multiple tasks concurrently.

Raises if any of them fail with an exception. Returns the results of all tasks.

Accepts the same options as parallel/3.

Example

iex> ExUtils.Runner.parallel!([1, 2, 3], &(&1 * 2))
[2, 4, 6]