# `ExUtils.Runner`
[🔗](https://github.com/sheharyarn/ex_utils/blob/main/lib/ex_utils/runner.ex#L1)

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:

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

# `background_opt`

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

# `parallel_opt`

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

# `background`

```elixir
@spec background([background_opt()], (-&gt; 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

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

# `group_results`

```elixir
@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

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

# `parallel`

```elixir
@spec parallel(Enumerable.t(), [parallel_opt()], (any() -&gt; 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

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

# `parallel!`

```elixir
@spec parallel!(Enumerable.t(), [parallel_opt()], (any() -&gt; 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

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

---

*Consult [api-reference.md](api-reference.md) for complete listing*
