Class: RateLimit::Htb::Bucket
- Inherits:
-
Object
- Object
- RateLimit::Htb::Bucket
- Defined in:
- lib/rate_limit/htb.rb
Instance Method Summary collapse
-
#blocking_take(amount) ⇒ Object
This method takes the specified amount of tokens from the bucket and blocks execution until it was successful.
-
#initialize(rate, parent = nil) ⇒ Bucket
constructor
Attributes.
-
#take(amount) ⇒ Object
Take the specified amount of tokens from this bucket.
Constructor Details
#initialize(rate, parent = nil) ⇒ Bucket
Attributes
-
rate- Amount of tokens generated every second. -
parent- Parent of this bucket. Any tokens taken from this bucket will also be taken from parent. When a parent is specified the rate of this bucket will be between the rate of this bucket and the rate of the parent. The parent bucket should have a larger rate than their children.
54 55 56 57 58 59 60 61 |
# File 'lib/rate_limit/htb.rb', line 54 def initialize(rate, parent = nil) @lock = Monitor.new @rate = rate || 0 @bucket_size = rate @parent = parent @tokens = rate @last_update_timestamp = Time.now end |
Instance Method Details
#blocking_take(amount) ⇒ Object
This method takes the specified amount of tokens from the bucket and blocks execution until it was successful.
This method tries to be smart about the amount of time it waits. It will wait the minimum time it takes to replenish enough tokens.
86 87 88 89 90 91 92 93 94 |
# File 'lib/rate_limit/htb.rb', line 86 def blocking_take(amount) # Try to take amount tokens from this bucket or wait for the tokens to replenish # do this until we could get the amount of tokens we wanted until take amount duration = amount.to_f / rate # rate is a method #puts "sleeping for #{duration}" sleep duration end end |
#take(amount) ⇒ Object
Take the specified amount of tokens from this bucket
If you want your code to block execution until it could take the specified amount of tokens use #blocking_take instead.
-
Returns :
-
true if the amount of tokens could be taken from this bucket or a parent.
-
70 71 72 73 74 75 76 77 78 79 |
# File 'lib/rate_limit/htb.rb', line 70 def take(amount) @lock.synchronize do replenish could_take = can_take? amount account amount if could_take could_take end end |