How to set retry count for Sidekiq with ActiveJob?

后端 未结 7 2055
走了就别回头了
走了就别回头了 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:32

    if you just use sidekiq, nerver change backend, monkey patch can help you

    module ActiveJob
      module QueueAdapters
        class SidekiqAdapter
          def enqueue(job)
            JobWrapper.sidekiq_options job.sidekiq_options_hash if job.sidekiq_options_hash
            JobWrapper.sidekiq_retry_in job.sidekiq_retry_in_block if job.sidekiq_retry_in_block
            Sidekiq::Client.push(
              'class' => JobWrapper,
              'wrapped' => job.class.to_s,
              'queue' => job.queue_name,
              'args'  => [ job.serialize ]
            )
          end
    
          def enqueue_at(job, timestamp)
            JobWrapper.sidekiq_options job.sidekiq_options_hash if job.sidekiq_options_hash
            JobWrapper.sidekiq_retry_in job.sidekiq_retry_in_block if job.sidekiq_retry_in_block
            Sidekiq::Client.push(
              'class' => JobWrapper,
              'wrapped' => job.class.to_s,
              'queue' => job.queue_name,
              'args'  => [ job.serialize ],
              'at'    => timestamp
            )
          end
        end
      end
    
      class Base
        class_attribute :sidekiq_options_hash
        class_attribute :sidekiq_retry_in_block
    
        def self.sidekiq_options(opts={})
          self.sidekiq_options_hash = opts
        end
    
        def self.sidekiq_retry_in(&block)
          self.sidekiq_retry_in_block = block
        end
      end
    end
    

    then, you can write like below:

    class BaseJob < ActiveJob::Base
    
      sidekiq_options retry: 2, queue: :low
      sidekiq_retry_in { |count, _| 3 * count }
    
      def perform; end
    end
    

    happy coding

提交回复
热议问题