Class: SimpleThrottle::TimeWindow::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_throttle/time_window/runner.rb

Overview

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

Instance Method Summary collapse

Constructor Details

#initialize(wait_s, count, sleep = ->(seconds) { sleep seconds }) ⇒ Runner

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



10
11
12
13
14
15
16
# 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

Instance Method Details

#deltaObject



40
41
42
43
# File 'lib/simple_throttle/time_window/runner.rb', line 40

def delta
  now = Time.now.to_f
  now - @last
end

#restart_window_if_neededObject



45
46
47
48
49
50
51
# 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(&block) ⇒ Object

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



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 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?Boolean

Returns:

  • (Boolean)


35
36
37
38
# File 'lib/simple_throttle/time_window/runner.rb', line 35

def within_limit?
  restart_window_if_needed
  @count < @max
end