Carrot v1.1.0 Carrot.Backoff View Source

Provides functions to facilitate exponential backoff.

Link to this section Summary

Functions

Creates a new Backoff struct based on provided options

Returns a new Backoff struct with updated state

Resets the backoff state

Schedules the next backoff interval

Link to this section Types

Link to this type option() View Source
option() :: {:max, pos_integer()} | {:min, pos_integer()}
Link to this type options() View Source
options() :: [option()]
Link to this type t() View Source
t() :: %Carrot.Backoff{
  max: pos_integer(),
  min: pos_integer(),
  state: pos_integer() | nil
}

Link to this section Functions

Creates a new Backoff struct based on provided options.

Options

  • :min - The minimum number of milliseconds for starting the backoff process (default: 1000)
  • :max - The maximum number of milliseconds before restarting the backoff process (default: 30_000)

Examples

iex> Carrot.Backoff.new()
%Carrot.Backoff{min: 1000, max: 30_000, state: nil}

iex> Carrot.Backoff.new(min: 100, max: 1000)
%Carrot.Backoff{min: 100, max: 1_000, state: nil}

Returns a new Backoff struct with updated state.

Examples

iex> backoff = Carrot.Backoff.new(min: 100, max: 400)
%Carrot.Backoff{min: 100, max: 400, state: nil}
iex> backoff = Carrot.Backoff.next(backoff)
%Carrot.Backoff{min: 100, max: 400, state: 100}
iex> backoff = Carrot.Backoff.next(backoff)
%Carrot.Backoff{min: 100, max: 400, state: 200}
iex> backoff = Carrot.Backoff.next(backoff)
%Carrot.Backoff{min: 100, max: 400, state: 400}
iex> _backoff = Carrot.Backoff.next(backoff)
%Carrot.Backoff{min: 100, max: 400, state: nil}

Resets the backoff state.

Example

iex> backoff = Carrot.Backoff.new()
%Carrot.Backoff{min: 1000, max: 30_000, state: nil}
iex> backoff = Carrot.Backoff.next(backoff)
%Carrot.Backoff{min: 1000, max: 30_000, state: 1000}
iex> _backoff = Carrot.Backoff.reset(backoff)
%Carrot.Backoff{min: 1000, max: 30_000, state: nil}
Link to this function schedule(backoff, pid, message) View Source
schedule(Carrot.Backoff.t(), pid(), any()) :: Carrot.Backoff.t()

Schedules the next backoff interval.

This function will send the given message to the given PID based on the current state of the Backoff struct.

Examples

iex> backoff = Carrot.Backoff.new(min: 100, max: 200)
%Carrot.Backoff{min: 100, max: 200, state: nil}
iex> backoff = Carrot.Backoff.next(backoff)
%Carrot.Backoff{min: 100, max: 200, state: 100}
iex> _backoff = Carrot.Backoff.schedule(backoff, self(), :connect)
%Carrot.Backoff{min: 100, max: 200, state: 100}
iex> receive do
...>   :connect ->
...>     :ok
...> end
:ok