module Resque::Plugins::Throttler

Public Class Methods

extended(other) click to toggle source
# File lib/resque/throttler.rb, line 8
def self.extended(other)
  other.instance_variable_set(:@rate_limits, {})
end

Public Instance Methods

gc_rate_limit_data_for_queue(queue) click to toggle source
# File lib/resque/throttler.rb, line 45
def gc_rate_limit_data_for_queue(queue)
  return unless queue_rate_limited?(queue)

  limit = rate_limit_for(queue)
  queue_key = "throttler:#{queue}_uuids"
  uuids = redis.smembers(queue_key)

  uuids.each do |uuid|
    job_ended_at = redis.hmget("throttler:jobs:#{uuid}", "ended_at")[0]
    if job_ended_at && Time.at(job_ended_at.to_i) < Time.now - limit[:per]
      redis.srem(queue_key, uuid)
      redis.del("throttler:jobs:#{uuid}")
    end
  end
end
pop(queue) click to toggle source
Calls superclass method
# File lib/resque/throttler.rb, line 12
def pop(queue)
  if queue_at_or_over_rate_limit?(queue)
    gc_rate_limit_data_for_queue(queue)
    nil
  else
    super
  end
end
queue_at_or_over_rate_limit?(queue) click to toggle source
# File lib/resque/throttler.rb, line 37
def queue_at_or_over_rate_limit?(queue)
  if queue_rate_limited?(queue)
    redis.scard("throttler:#{queue}_uuids") >= rate_limit_for(queue)[:at]
  else
    false
  end
end
queue_rate_limited?(queue) click to toggle source
# File lib/resque/throttler.rb, line 33
def queue_rate_limited?(queue)
  !!@rate_limits[queue.to_s]
end
rate_limit(queue, options={}) click to toggle source
# File lib/resque/throttler.rb, line 21
def rate_limit(queue, options={})
  if options.keys.sort != [:at, :per]
    raise ArgumentError.new("Mising either :at or :per in options") 
  end

  @rate_limits[queue.to_s] = options
end
rate_limit_for(queue) click to toggle source
# File lib/resque/throttler.rb, line 29
def rate_limit_for(queue)
  @rate_limits[queue.to_s]
end