Class: QuartzTorrent::RateLimit

Inherits:
Object
  • Object
show all
Defined in:
lib/quartz_torrent/ratelimit.rb

Overview

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(unitsPerSecond, upperLimit, initialValue) ⇒ RateLimit

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.



12
13
14
15
16
17
18
# 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

Instance Attribute Details

#unitsPerSecondObject

Return the limit in units per second



21
22
23
# File 'lib/quartz_torrent/ratelimit.rb', line 21

def unitsPerSecond
  @unitsPerSecond
end

Instance Method Details

#availObject

How much is in the pool.



29
30
31
32
# File 'lib/quartz_torrent/ratelimit.rb', line 29

def avail
  updatePool
  @pool
end

#to_sObject



40
41
42
43
44
# File 'lib/quartz_torrent/ratelimit.rb', line 40

def to_s
  s = ""
  s << "units/sec: #{@unitsPerSecond}, avail: #{avail}, upperlim: #{@upperLimit}"
  s
end

#withdraw(n) ⇒ Object

Withdraw this much from the pool.



35
36
37
38
# File 'lib/quartz_torrent/ratelimit.rb', line 35

def withdraw(n)
  updatePool
  @pool -= n
end