Skip to content

Instantly share code, notes, and snippets.

@jppommet
Forked from eparreno/sidekiq_delete_jobs.md
Created August 26, 2021 03:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jppommet/0cbf3b2eb4cdd77ccd8ebb028514ef4a to your computer and use it in GitHub Desktop.
Save jppommet/0cbf3b2eb4cdd77ccd8ebb028514ef4a to your computer and use it in GitHub Desktop.
How to delete Sidekiq jobs in a Rails app using ActiveJobs

How to delete Sidekiq jobs in a Rails app using ActiveJobs

Sidekiq jobs can be enqueued or scheduled. Enqueued means that they are gonna be picked up as soon as possible, scheduled jobs will be enqueued at some specific time.

job_id and jid

When using ActiveJobs, Rails will return a job_id after sending the job to ActiveJobs

job = UserMailer.send_invite(params).deliver_later
job.job_id => "9fb7b1f3-0159-49dd-b886-dfb8df991cd6"

Keep in mind that this is not the id Sidekiq uses to reference jobs internally. To get the Sidekiq jid

# enqueued jobs
job = UserMailer.send_invite(params).deliver_later
Sidekiq::Queue.new("mailers").find { |job_id| job.job_id }.item["jid"]

# scheduled jobs
job = UserMailer.send_invite(params).deliver_later(wait: 1.hour)
Sidekiq::ScheduledSet.new.find { |job_id| job.job_id }.item["jid"]

Enqueued jobs

Here's a typical example in a Rails app

job = UserMailer.send_invite(params).deliver_later

That jobs will go straight to the queue and will get processed as soon as possible. Keep in mind that Sidekiq is fast as hell so if there are enough resources that job will be executed with virtually no delay, so it's almost impossible to delete a job from the queue unless Sidekiq is busy processing other jobs, that will give you some time to delete the job.

queue = Sidekiq::Queue.new("mailer")
queue.each do |job|
  # using jid
  job.delete if job.jid == 'sidekiq_job_id'
  # using job_id
  job.delete if job.job_id == 'rails_job_id'
end

Scheduled jobs

In that case you'll have a bit more time to delete the job ;)

job = UserMailer.send_invite(params).deliver_later(wait: 1.hour)
ss = Sidekiq::ScheduledSet.new
ss.select { |job_id| job.job_id }.each(&:delete)

or using the jid

jid = Sidekiq::ScheduledSet.new.find { |job_id| job.job_id }.item["jid"]
Sidekiq::ScheduledSet.new.find_job(jid).delete

or matching jobs by class instead of by ID

ss = Sidekiq::ScheduledSet.new
jobs = ss.select {|job| job.klass == 'SomeWorker' }
jobs.each(&:delete)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment