136

I've this worker that runs for ever.

class Worker
  include Sidekiq::Worker
  sidekiq_options queue: "infinity", retry: true

  def perform(params)
    # ...
    self.class.perform_in(30.seconds, params)
  end
end

The problem is that I load workers on start up, like this. config/initializers/load_workers.rb

Rails.application.config.after_initialize do  
  if ENV["SIDEKIQ"] == "1"
    Worker.perform_async({})
  end
end

Using this to start sidekiq SIDEKIQ=1 sidekiq --verbose --environment production -C config/sidekiq.yml.

This means that old workers as to stop, both those currently running but also the ones being rescheduled.

I tried running this on start up (just before loading new works), but that didn't work.

q = []
q += Sidekiq::RetrySet.new.select { |job| job.klass.match(/Worker/) }
q += Sidekiq::Queue.new("infinity").select { |job| job.klass.match(/Worker/) }
q += Sidekiq::ScheduledSet.new.select { |job| job.klass.match(/Worker/) }
q.each(&:delete)

After 5-ish deploys there are bunch of duplicate workers in the queue scheduled for later. So, is there a way to clear everyting in one queue and prevent already running jobs from rescheduling?

I'm using sidekiq 3.0.

Linus Oleander
  • 17,746
  • 15
  • 69
  • 102

5 Answers5

197

Deletes all Jobs in a Queue, by removing the queue.

require 'sidekiq/api' # for the case of rails console

Sidekiq::Queue.new("infinity").clear
Sidekiq::RetrySet.new.clear
Sidekiq::ScheduledSet.new.clear
Alex Antonov
  • 14,134
  • 7
  • 65
  • 142
Ranjithkumar Ravi
  • 3,352
  • 2
  • 20
  • 22
178

This will clear all queues, schedules and retries:

require 'sidekiq/api'
Sidekiq::Queue.all.each(&:clear)
Sidekiq::RetrySet.new.clear
Sidekiq::ScheduledSet.new.clear
Sidekiq::DeadSet.new.clear
iGEL
  • 16,540
  • 11
  • 60
  • 74
  • 1
    Thanks this worked like a charm i was into an emergency haha , the sidekick was with waaaaaay too many workers on the queue this worked as i was expecting since i was looking for `kill` like command – d1jhoni1b Mar 30 '18 at 17:03
  • 1
    Perfect, just adding that in my env I had to `require 'sidekiq/api'` on console to work. – bonafernando Jan 02 '20 at 16:50
21

Works for me for most sidekiq versions:

Sidekiq::RetrySet.new.clear

Sidekiq::ScheduledSet.new.clear

Clear statistics (Optional)

Sidekiq::Stats.new.reset
rusllonrails
  • 5,586
  • 3
  • 34
  • 27
1

There is one more convenient way to clear all Sidekiq queues and sets for local env: Sidekiq.redis(&:flushdb)

Basically, it just flushes Redis that is configured for Sidekiq, so I would avoid using it in a non-local environment, as it can also remove some data you store in Redis. Anyways, it can be useful for the development or when you have a separate Redis instance for Sidekiq. And it's just one line instead of four.

ARtoriouS
  • 73
  • 5
-4

You can clear your queue by running this code although there would be built-in methods.

queue = Sidekiq::Queue.new
queue.each do |job|
  job.delete 
end