Sidekiq work conditions

2019-08-08 06:42发布

问题:

On my application I have 25 workers that are randomly used by different users' actions.

Only one simultaneous (active / busy) work is allowed by each user.

It can't be blocked on the controller because the idea is not to block the action creation. Actions need to be created but hold in line till all previos requests by the same user are processed and only after that a worker will be (re)-assigned for the same user.

If another user, in the meantime, requests a job creation, it should start instantly if at least one of the 24 remaining workers are available.

Is there any way to look for the queue line and use its parameters to build the processing condition?

Thanks

回答1:

You can use Sidekiq Unique Jobs

with this approach only 1 job with the same params will be simultaneous present.

so create model

class UserJobs
  belongs_to :user
end

class User
  has_many :user_jobs
end

class Worker
  sidekiq_options unique: true

  def perform params
    user = User.find(params[:id])
    user.user_jobs.order('id asc').each do |job|
      job.worker_class.constantize.new.perform(job.params)
      job.destroy
    end
  end
end

than when you need run any job for user do:

user.user_jobs.create worker_class: Klass, params: params
Worker.perform_async(user_id: user.id)