Class: Sidekiq::Workers

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/sidekiq/api.rb

Overview

Programmatic access to the current active worker set.

WARNING WARNING WARNING

This is live data that can change every millisecond. If you call #size => 5 and then expect #each to be called 5 times, you’re going to have a bad time.

workers = Sidekiq::Workers.new
workers.size => 2
workers.each do |process_id, thread_id, work|
  # process_id is a unique identifier per Sidekiq process
  # thread_id is a unique identifier per thread
  # work is a Hash which looks like:
  # { 'queue' => name, 'run_at' => timestamp, 'payload' => msg }
  # run_at is an epoch Integer.
end

Instance Method Summary collapse

Instance Method Details

#eachObject



771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
# File 'lib/sidekiq/api.rb', line 771

def each
  Sidekiq.redis do |conn|
    procs = conn.smembers('processes')
    procs.sort.each do |key|
      valid, workers = conn.pipelined do
        conn.exists(key)
        conn.hgetall("#{key}:workers")
      end
      next unless valid
      workers.each_pair do |tid, json|
        yield key, tid, Sidekiq.load_json(json)
      end
    end
  end
end

#sizeObject

Note that #size is only as accurate as Sidekiq’s heartbeat, which happens every 5 seconds. It is NOT real-time.

Not very efficient if you have lots of Sidekiq processes but the alternative is a global counter which can easily get out of sync with crashy processes.



793
794
795
796
797
798
799
800
801
802
803
804
805
806
# File 'lib/sidekiq/api.rb', line 793

def size
  Sidekiq.redis do |conn|
    procs = conn.smembers('processes')
    if procs.empty?
      0
    else
      conn.pipelined do
        procs.each do |key|
          conn.hget(key, 'busy')
        end
      end.map(&:to_i).inject(:+)
    end
  end
end