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
@type background_opt() :: {:delay, non_neg_integer()}
@type parallel_opt() :: {:concurrency, pos_integer()} | {:timeout, timeout()} | {:on_timeout, :exit | :kill_task}
Functions
@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>}
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]}
@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 to5.:timeout- the maximum time in milliseconds each task may run. Defaults to10_000.:on_timeout- either:exitor:kill_task.
Example
iex> ExUtils.Runner.parallel([1, 2, 3], fn number -> number * 2 end)
[ok: 2, ok: 4, ok: 6]
@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]