简体   繁体   中英

Sidekiq Job - How can I launch a job and each time change the parameter used?

I would like to launch a job which is going to calculate the points of each user of my web-App. Here is the problem, I would like to launch it automatically with sidekiq-scheduler. But I have trouble to understand how I can launch my job with an argument which is going to change. I mean I have to calculate the amount of points for each user, so the argument is going to change and take different user_id.

Here is my code:

class PointsjoueurJob < ApplicationJob
  queue_as :default
  def perform(user_id)
@user = User.find(user_id)
    @playerseason = PlayerSeason.where(user_id: @user.id)
    @forecasts = Forecast.where(player_season_id: @playerseason)
     points = []
     @forecasts.each do |forecast|
       if forecast.points_win.present? || forecast.points_lose.present?
         if forecast.points_win.present?
           points << forecast.points_win
         else forecast.points_lose.present?
           points << forecast.points_lose
         end
         @playerseason.update(number_of_points: points.sum)
       else
       end
     end
 end

Right now if I want to launch it, I have to go to my console then type:

PointsjoueurJob.perform_now(1)

But I want to schedule this with sidekiq-scheduler. The goal is to trigger the work everyday at 01h00 (cron: '0 1 * * *')but I don't know how to set-up the argument in order for the job to iterate trough all the users.

Thank you by advance.

Assuming that you want to recalculate all users' totals, you can create a separate 'wrapper' job, which is scheduled, that in turn enqueues the individual recalculation jobs:

class RecalcPointsJob < ApplicationJob
  queue_as :default

  def perform
    User.find_each do |u|
      PointsjoueurJob.perform_later(u.id)
    end
  end
end

If you are after a subset of users instead, substitute User.where() or User.find_by() .

You can generate a Task and use whenever , then setup it.
on task you can write this:

rails g task test cron

namespace :test do
  task :cron do
    User.find_each do |u|
      PointsjoueurJob.perform_async(u.id)
    end
  end
end

then in config/schedule.rb after install whenever

every '0 1 * * *' do
  rake "test:cron"
end

then

whenever --update-crontab

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM