module RateThrottle

Example

# throttling 10% workload.
10000.times do 
  RateThrottle.throttle(0.1) do
    # do something
  end
end

Public Class Methods

calc_sleep_time(rate, time) click to toggle source
# File lib/rate_throttle.rb, line 18
def self.calc_sleep_time(rate, time)
  if time > 0.0
    return time * ( 1- rate ) / rate
  else
    return 0
  end
end
throttle(rate, &block) click to toggle source
# File lib/rate_throttle.rb, line 11
def self.throttle(rate, &block)
  start = Time.now
  block.call
  sleep_time = self.calc_sleep_time(rate, Time.now - start)
  sleep(sleep_time)
end