class QuartzTorrent::RateLimit

This class can be used to limit the rate at which work is done.

Attributes

unitsPerSecond[R]

Return the limit in units per second

Public Class Methods

new(unitsPerSecond, upperLimit, initialValue) click to toggle source

unitsPerSecond: Each second this many units are added to a pool. At any time

up to the number of units in the pool may be withdrawn.

upperLimit: The maximum size of the pool. This controls how bursty the rate is.

For example, if the rate is 1/s and the limit is 5, then if there was no withdrawals
for 5 seconds, then the max pool size is reached, and the next withdrawal may be 5, meaning
5 units could be used instantaneously. However the average for the last 5 seconds is still 1/s.

initialValue: Initial size of the pool.

# File lib/quartz_torrent/ratelimit.rb, line 12
def initialize(unitsPerSecond, upperLimit, initialValue)
  @unitsPerSecond = unitsPerSecond.to_f
  @upperLimit = upperLimit.to_f
  @initialValue = initialValue.to_f
  @pool = @initialValue
  @time = Time.new
end

Public Instance Methods

avail() click to toggle source

How much is in the pool.

# File lib/quartz_torrent/ratelimit.rb, line 29
def avail
  updatePool
  @pool
end
to_s() click to toggle source
# File lib/quartz_torrent/ratelimit.rb, line 40
def to_s
  s = ""
  s << "units/sec: #{@unitsPerSecond}, avail: #{avail}, upperlim: #{@upperLimit}"
  s
end
unitsPerSecond=(v) click to toggle source

Set the limit in units per second.

# File lib/quartz_torrent/ratelimit.rb, line 24
def unitsPerSecond=(v)
  @unitsPerSecond = v.to_f
end
withdraw(n) click to toggle source

Withdraw this much from the pool.

# File lib/quartz_torrent/ratelimit.rb, line 35
def withdraw(n)
  updatePool
  @pool -= n
end

Private Instance Methods

updatePool() click to toggle source
# File lib/quartz_torrent/ratelimit.rb, line 47
def updatePool
  now = Time.new
  @pool = @pool + (now - @time)*@unitsPerSecond
  @pool = @upperLimit if @pool > @upperLimit
  @time = now
end