Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sidekiq uniqueness jobs. Permits to avoid duplicated jobs already enqueued or scheduled.
# frozen_string_literal: true
require 'sidekiq/api'
module UniquenessJob
extend ActiveSupport::Concern
included do
class << self
alias_method :client_push_old, :client_push
def client_push(item)
is_test = Rails.env.test?
job = is_test ? find_similar_test_jobs(item) : find_similar_job(item)
job ? job['jid'] : client_push_old(item)
end
end
end
class_methods do
private
def find_similar_job(item)
queue_name = get_sidekiq_options['queue']
queue = Sidekiq::Queue.new(queue_name)
job = queue.map(&:item).find do |j|
j['class'] == item['class'].to_s && j['args'] == item['args']
end
job || find_similar_scheduled_job(item, queue_name)
end
def find_similar_scheduled_job(item, queue_name)
ss = Sidekiq::ScheduledSet.new
ss.map(&:item).find do |j|
j['class'] == item['class'].to_s &&
j['args'] == item['args'] &&
j['queue'] == queue_name
end
end
end
class_methods do
def find_similar_test_jobs(item)
item['class'].jobs.find do |j|
j['args'] == item['args']
end
end
end
end
class UpdateArticleInfoJob
include Sidekiq::Worker
include UniquenessJob
def perform(article_id)
res = Articles::UpdateInfo.call(article: Article.find(article_id))
raise res.message unless res.success?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment