How to set retry count for Sidekiq with ActiveJob?

后端 未结 7 2034
走了就别回头了
走了就别回头了 2021-02-07 01:50

From the Rails API, I found ActiveJob can retry_job interval:

my_job_instance.enqueue
my_job_instance.enqueue wait: 5.minutes
my_job_instance.enqueue queue: :imp         


        
7条回答
  •  北海茫月
    2021-02-07 02:39

    There is a activejob-retry gem which does the job

    class SiteScrapperJob < ActiveJob::Base
      include ActiveJob::Retry.new(limit: 5, strategy: :exponential)
    
      def perform(*args)
        # raise ErrorLoadingSite if cannot scrape
      end
    end
    

    Another option is to use sidekiq middleware:

    First define job_options class-method which will be available in the subclasses:

    class ApplicationJob < ActiveJob::Base
      def self.job_options(options)
        @job_options = options
      end
    
      def self.get_job_options
        @job_options || {}
      end
    end
    

    Add middleware which reads job_options from the jobs's class and writes them to the job item for sidekiq:

    module Sidekiq
     class JobOptionsMiddleware
    
       def call(job_wrapper, item, queue, redis_pool)
         job = item['args'][0]['job_class'].constantize
    
         job.get_job_options
           .each{ |option, value| item[option] = value if item[option].nil? }
    
         yield
       end
    
     end
    
     # in sidekiq initializer
    
     Sidekiq.configure_client do |config|
       config.client_middleware do |chain|
         chain.add Sidekiq::JobOptionsMiddleware
       end
     end
    

    And finally

     class SiteScrapperJob < ApplicationJob
       job_options retry: 5
    
       def perform
         # your code
       end
     end
    

提交回复
热议问题