Unique Oban jobs with period still seems to insert into DB

I have this function that returns a list of things from my DB, but I also want to enqueue a backfill to an API I use.

  def search_games_by_term(search_term) do
    keys = [:search_term]

    # Setting unique period to 604800 in seconds ==  1 week.
    %{search_term: search_term}
    |> Gamedrop.Workers.ApiSearch.new(
      unique: [fields: [:args, :worker], keys: keys, period: 604_800]
    )
    |> Oban.insert()
    |> IO.inspect()

    list_games(search_term)
  end

My worker looks like this:

defmodule Gamedrop.Workers.ApiSearch do
  use Oban.Worker, queue: :default

  @impl Oban.Worker
  def perform(%Oban.Job{args: %{"search_term" => search_term} = _args}) do
    IO.inspect("Oban workers says...")
    IO.inspect(search_term)
    :ok
  end
end

Given a search_term I only want to reach out to this API at most once a week. I see the job inserted in oban_jobs DB table, and when I immediately run the code again, it does not create a second record. I see a conflict?: true in the unsuccessful second insert which is great. But after a bit the records in the oban_jobs table wipes and I can once again enqueue this job with the same search term as before.

Appreciate the help, thanks!

My code above was correct. I just needed to make sure the pruner didn’t nuke the oban_jobs table so there was something to unique check against!

Here’s the change:

config :my_app, Oban,
  repo: MyApp.Repo,
  # Setting unique period to 604800 in seconds ==  1 week.
  plugins: [{Oban.Plugins.Pruner, max_age: 604_800}],
  queues: [default: 1]
4 Likes

@sergio good to see you resolved the issue. In the future be sure to tag with oban rather than phoenix to notify interested parties (me :grin:).

3 Likes