Class: Strangler
- Inherits:
-
Object
- Object
- Strangler
- Defined in:
- lib/strangler.rb
Overview
Limit calls to an API by sleeping
Constant Summary collapse
- VERSION =
"1.0.6"
Instance Method Summary collapse
-
#initialize(minimum_delay_secs = 1.1) ⇒ Strangler
constructor
Set the minimum delay between calls.
-
#throttle! ⇒ Object
Ensure that calls do not exceed the rate limit by delaying thread We assume that we must wait at least @minimum_delay_seconds since end of last call Note that the delay is measured from the end of any previous call.
Constructor Details
#initialize(minimum_delay_secs = 1.1) ⇒ Strangler
Set the minimum delay between calls
9 10 11 12 13 |
# File 'lib/strangler.rb', line 9 def initialize( minimum_delay_secs = 1.1 ) @minimum_delay_secs = minimum_delay_secs @semaphore = Mutex.new @next_call = nil # Earliest time a new block can be executed end |
Instance Method Details
#throttle! ⇒ Object
Ensure that calls do not exceed the rate limit by delaying thread We assume that we must wait at least @minimum_delay_seconds since end of last call Note that the delay is measured from the end of any previous call
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/strangler.rb', line 19 def throttle! raise ArgumentError, "Must supply a block to throttle!" unless block_given? @semaphore.synchronize do unless @next_call.nil? while Time.now < @next_call doze_time = @next_call - Time.now sleep doze_time end end begin yield # Do the stuff ensure @next_call = Time.now + @minimum_delay_secs end end end |