Class: Polyphony::Throttler

Inherits:
Object show all
Defined in:
lib/polyphony/core/throttler.rb

Overview

Implements general-purpose throttling

Instance Method Summary collapse

Constructor Details

#initialize(rate) ⇒ Throttler

Initializes a throttler instance with the given rate.

Parameters:

  • rate (Number)

    throttler rate in times per second



9
10
11
12
13
# File 'lib/polyphony/core/throttler.rb', line 9

def initialize(rate)
  @rate = rate_from_argument(rate)
  @min_dt = 1.0 / @rate
  @next_time = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
end

Instance Method Details

#callany Also known as: process

Invokes the throttler with the given block. The throttler will automatically introduce a delay to keep to the maximum specified rate. The throttler instance is passed to the given block.

Returns:

  • (any)

    given block's return value



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/polyphony/core/throttler.rb', line 20

def call
  now = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
  delta = @next_time - now
  Polyphony.backend_sleep(delta) if delta > 0
  result = yield self

  while true
    @next_time += @min_dt
    break if @next_time > now
  end

  result
end