Tom Rossi
Tom Rossi

Reputation: 12066

Setting priority with ActiveJob when using Delayed::Job

How do you set the delayed job priority when using ActiveJob to enqueue your jobs?

class GuestsCleanupJob < ApplicationJob
  queue_as :high_priority

  def perform(*guests)
    # Do something later
  end
end

Upvotes: 10

Views: 2670

Answers (4)

Alexander Quiceno
Alexander Quiceno

Reputation: 41

To follow the pattern of queue_as you could also use queue_with_priority like:

class GuestsCleanupJob < ApplicationJob
  queue_as :high_priority
  queue_with_priority 1

  def perform(*guests)
    # Do something later
  end
end


https://api.rubyonrails.org/classes/ActiveJob/QueuePriority/ClassMethods.html#method-i-queue_with_priority

Upvotes: 2

Nicholas Stock
Nicholas Stock

Reputation: 61

defining an instance method that defines priority works, however is doesn't allow me to overload the value. Given this class

class GuestsCleanupJob < ApplicationJob
  queue_as :high_priority

  def priority
    1
  end

  def perform(*guests)
    # Do something later
  end
end

if I run

GuestsCleanupJob.set(priority: 55).perform_later(user, lead) # priority set to 1 not 55

It will queue up a job with priority 1, and ignore the 55 I passed.

That didn't provide enough control for my use-case so instead I did.

class GuestsCleanupJob < ApplicationJob
  queue_as :high_priority

  def default_priority
    1
  end

  def priority
    @priority || default_priority
  end

  def perform(*guests)
    # Do something later
  end
end

Using the above code, by default the priority will be set to one, but I can use my

GuestsCleanupJob.set(priority: 55).perform_later(user, lead) # priority set to 55

Upvotes: 4

wsa
wsa

Reputation: 123

The solution using Delayed::Worker.queue_attributes, looks ok and it is documented, but it didn't work for me ... All the jobs had priority=0 regardless the queue priority set in queue_attributes. This worked for me:

class GuestsCleanupJob < ApplicationJob
  queue_as :high_priority

  def priority
    1
  end

  def perform(*guests)
    # Do something later
  end
end

Upvotes: 3

Tom Rossi
Tom Rossi

Reputation: 12066

It took me a while, but I found this method in the Delayed::Job documentation:

Delayed::Worker.queue_attributes = {
  default:       { priority: 11 },
  high_priority: { priority: 1 },
  low_priority:  { priority: 75 }
}

I've added this to my initializers and just wanted to share if anyone else runs into this!

Upvotes: 15

Related Questions