Class: Throttle::TimeWindow::Runner
- Inherits:
-
Object
- Object
- Throttle::TimeWindow::Runner
- Defined in:
- lib/throttle/time_window/runner.rb
Overview
Executes at most a number of times within given time window.
Instance Method Summary collapse
-
#initialize(wait_s, count, sleep = ->(seconds) { sleep seconds }) ⇒ Runner
constructor
Parameters:
wait_s: minimum number os seconds betweencountblock invocationscount: maximum number of times block may be called betweenwait_sseconds. -
#run(&block) ⇒ Object
Run given
blockeither immediately (if allowed) or after sleep.
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/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
#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 34 35 36 37 38 |
# File 'lib/throttle/time_window/runner.rb', line 19 def run(&block) #puts "count: #{@count}, delta: #{Time.now.to_f - @last}" now = Time.now.to_f delta = now - @last if delta >= @wait_s #puts "resetting" @last = now @count = 0 end if @count >= @max sleep_interval = @wait_s - delta #puts "throttle forced sleep for #{sleep_interval}" @sleep.call sleep_interval end @count += 1 #puts "running " yield end |