Class: Hedra::RateLimiter
- Inherits:
-
Object
- Object
- Hedra::RateLimiter
- Defined in:
- lib/hedra/rate_limiter.rb
Overview
Token bucket rate limiter
Instance Method Summary collapse
- #acquire ⇒ Object
-
#initialize(rate_string) ⇒ RateLimiter
constructor
A new instance of RateLimiter.
Constructor Details
#initialize(rate_string) ⇒ RateLimiter
Returns a new instance of RateLimiter.
6 7 8 9 10 11 12 |
# File 'lib/hedra/rate_limiter.rb', line 6 def initialize(rate_string) @requests, period = parse_rate(rate_string) @period = period_to_seconds(period) @tokens = @requests @last_refill = Time.now @mutex = Mutex.new end |
Instance Method Details
#acquire ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/hedra/rate_limiter.rb', line 14 def acquire @mutex.synchronize do refill_tokens if @tokens >= 1 @tokens -= 1 return end # Wait until we have tokens sleep_time = @period / @requests sleep(sleep_time) refill_tokens @tokens -= 1 end end |