How to specify a default queue to use for all jobs with Resque in Rails?

独自空忆成欢 提交于 2019-12-21 16:57:44

问题


I want all the enqueue calls to default to a certain queue unless specified otherwise so it's DRY and easier to maintain. In order to specify a queue, the documentation said to define a variable @queue = X within the class. So, I tried doing the following and it didn't work, any ideas?

class ResqueJob
  class << self; attr_accessor :queue end
  @queue = :app
end

class ChildJob < ResqueJob
  def self.perform
  end
end

Resque.enqueue(ChildJob)

Resque::NoQueueError: Jobs must be placed onto a queue.
from /Library/Ruby/Gems/1.8/gems/resque-1.10.0/lib/resque/job.rb:44:in `create'
from /Library/Ruby/Gems/1.8/gems/resque-1.10.0/lib/resque.rb:206:in `enqueue'
from (irb):5

回答1:


In ruby, class variables are not inherited. That is why Resque can't find your @queue variable.

You should instead define self.queue in your parent class. Resque first checks for the presence of @queue, but looks secondarily for a queue class method:

class ResqueJob
  def self.queue; :app; end
end

class ChildJob < ResqueJob
  def self.perform; ...; end
end



回答2:


If you want to do this with a mixin, you can do it like this:

module ResqueJob
  extend ActiveSupport::Concern

  module ClassMethods
    def queue
      @queue || :interactor_operations
    end
  end
end

class ChildJob
  include ResqueJob

  def self.perfom
  end
end

(if you don't have activesupport, you can also do this the classical ruby way, but I find this way easier, so well worth the weight ;) )




回答3:


Try a mixin. Something like this:

module ResqueJob
  def initQueue
    @queue = :app
  end 
end

class ChildJob 
  extend ResqueJob

  initQueue

  def self.perform
  end
end

Resque.enqueue(ChildJob)


来源:https://stackoverflow.com/questions/5102113/how-to-specify-a-default-queue-to-use-for-all-jobs-with-resque-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!