Background jobs with Oban

Oban has become to go-to library for background jobs in Phoenix. Even though you could argue that you could accomplish the same functianlity with pure Elixir, using Oban abstracts a lot of complexity away.

Oban persists the jobs in a Postgresql table so you dont need to worry about what happens to scheduled tasks during deployment.

Installation

To install Oban, run the command:

mix saaskit.gen.kit oban

And since it stores the jobs in the dtabase, there is a migration that needs to be run.

mix ecto.migrate

Usage

Example

defp maybe_schedule_onboarding_emails({:ok, user} = result) do
  %{id: user.id, step: "one"}
  |> Tutorial.Users.OnboardingWorker.new(schedule_in: @one_day)
  |> Oban.insert()

  %{id: user.id, step: "two"}
  |> Tutorial.Users.OnboardingWorker.new(schedule_in: @two_days)
  |> Oban.insert()
end

In this example, I would like to send an onboarding email after the user has signed up.

And then create a worker:

defmodule Tutorial.Users.OnboardingWorker do
  use Oban.Worker, unique: [fields: [:args, :worker]]

  alias Tutorial.Users
  alias Tutorial.Users.UserNotifier

  @impl Oban.Worker
  def perform(%Oban.Job{args: %{"id" => user_id, "step" => step}}) do
    user = Users.get_user!(id)

    UserNotifier.deliver_onboarding_email(step, user)

    :ok
  end
end

Visit the official documentation to learn more.