class SimpleThrottle::TimeWindow::Runner

Executes at most a number of times within given time window.

Public Class Methods

new(wait_s, count, sleep = ->(seconds) { sleep seconds } click to toggle source

Parameters: wait_s: minimum number os seconds between count block invocations count: maximum number of times block may be called between wait_s seconds

# File lib/simple_throttle/time_window/runner.rb, line 10
def initialize(wait_s, count, sleep = ->(seconds) { sleep seconds })
  @max = count
  @last = 0.0 #last invocation timestamp
  @count = 0
  @wait_s = wait_s.to_f
  @sleep = sleep
end

Public Instance Methods

delta() click to toggle source
# File lib/simple_throttle/time_window/runner.rb, line 40
def delta
  now = Time.now.to_f
  now - @last
end
restart_window_if_needed() click to toggle source
# File lib/simple_throttle/time_window/runner.rb, line 45
def restart_window_if_needed
  if delta >= @wait_s
    #puts "resetting"
    @last = Time.now.to_f
    @count = 0
  end
end
run() { || ... } click to toggle source

Run given block either immediately (if allowed) or after sleep.

# File lib/simple_throttle/time_window/runner.rb, line 19
def run(&block)
  #puts "count: #{@count}, delta: #{Time.now.to_f - @last}"

  restart_window_if_needed

  if !within_limit?
    sleep_interval = @wait_s - delta
    #puts "simple_throttle forced sleep for #{sleep_interval}"
    @sleep.call sleep_interval
  end

  @count += 1
  #puts "running "
  yield
end
within_limit?() click to toggle source
# File lib/simple_throttle/time_window/runner.rb, line 35
def within_limit?
  restart_window_if_needed
  @count < @max
end