Search code examples
ruby-on-railssidekiq

how to delete a job in sidekiq


I am using sidekiq in my rails app. Users of my app create reports that start a sidekiq job. However, sometimes users want to be able to cancel "processing" reports. Deleting the report is easy but I also need to be able to delete the sidekiq job as well.

So far I have been able to get a list of workers like so:

workers = Sidekiq::Workers.new

and each worker has args that include a report_id so I can identify which job belongs to which report. However, I'm not sure how to actually delete the job. It should be noted that I want to delete the job whether it is currently busy, or set in retry.


Solution

  • According to this Sidekiq documentation page to delete a job with a single id you need to iterate the queue and call .delete on it.

    queue = Sidekiq::Queue.new("mailer")
    queue.each do |job|
      job.klass # => 'MyWorker'
      job.args # => [1, 2, 3]
      job.delete if job.jid == 'abcdef1234567890'
    end
    

    There is also a plugin called sidekiq-status that provides you the ability to cancel a single job

    scheduled_job_id = MyJob.perform_in 3600
    Sidekiq::Status.cancel scheduled_job_id #=> true