Class: GemCP::RateLimiter
- Inherits:
-
Object
- Object
- GemCP::RateLimiter
- Defined in:
- lib/gemcp/rate_limiter.rb
Overview
Thread-safe rate limiter that enforces a minimum interval between calls. Uses a Mutex to prevent interleaving during the sleep gap.
Instance Method Summary collapse
-
#initialize(requests_per_second:) ⇒ RateLimiter
constructor
A new instance of RateLimiter.
-
#wait ⇒ void
Blocks until enough time has elapsed since the last call.
Constructor Details
#initialize(requests_per_second:) ⇒ RateLimiter
Returns a new instance of RateLimiter.
8 9 10 11 12 |
# File 'lib/gemcp/rate_limiter.rb', line 8 def initialize(requests_per_second:) @minimum_interval = requests_per_second.positive? ? 1.0 / requests_per_second : 0.0 @last_request_at = nil @mutex = Mutex.new end |
Instance Method Details
#wait ⇒ void
This method returns an undefined value.
Blocks until enough time has elapsed since the last call. Safe to call from multiple threads.
18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/gemcp/rate_limiter.rb', line 18 def wait @mutex.synchronize do now = Process.clock_gettime(Process::CLOCK_MONOTONIC) if @last_request_at sleep_for = @minimum_interval - (now - @last_request_at) sleep(sleep_for) if sleep_for.positive? end @last_request_at = Process.clock_gettime(Process::CLOCK_MONOTONIC) end end |