Ant.Worker behaviour (Ant v1.0.0)

A background job, and the process that runs it.

use Ant.Worker in a module that implements perform/1 to define a job:

defmodule MyWorker do
  use Ant.Worker, max_attempts: 3, timeout: :timer.seconds(30)

  def perform(%{args: args} = _worker), do: :ok
end

MyWorker.perform_async(%{email: "user@example.com"})

perform/1 receives the Ant.Worker struct and must return :ok or {:ok, result}; anything else counts as a failed attempt, as do exceptions, throws, exits and running past the timeout. A failed attempt is retried while the worker has attempts left, and marked as :failed afterwards.

Options accepted by use Ant.Worker and, per job, by perform_async/2:

  • :queue - the queue that runs the job. Defaults to the first configured queue.
  • :max_attempts - how many times the job may run. Defaults to 1.
  • :timeout - how long a single attempt may take, in milliseconds. Defaults to :infinity.
  • :unique - prevents duplicate jobs, see Ant.WorkerUniquenessChecker.

The delay before a retry defaults to ten seconds times the number of attempts made, and can be replaced by implementing the optional calculate_delay/1 callback.

Summary

Functions

Returns a specification to start this module under a supervisor.

Callback implementation for GenServer.init/1.

Types

@type t() :: %Ant.Worker{
  args: map(),
  attempts: non_neg_integer(),
  errors: [map()],
  id: non_neg_integer(),
  opts: keyword(),
  queue_name: atom() | String.t(),
  scheduled_at: DateTime.t(),
  status:
    :enqueued
    | :running
    | :scheduled
    | :completed
    | :failed
    | :retrying
    | :cancelled,
  updated_at: DateTime.t(),
  worker_module: module()
}

Callbacks

Link to this callback

calculate_delay(worker)

(optional)
@callback calculate_delay(worker :: t()) :: non_neg_integer()
Link to this callback

perform(worker)

@callback perform(worker :: t()) :: :ok | {:ok, any()} | {:error, any()}

Functions

Link to this function

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

Link to this function

default_queue_name()

Callback implementation for GenServer.init/1.

Link to this function

perform(worker_pid)

Link to this function

start_link(worker)