Sha256: 5044e0aa26f3cb9eb95e0040ed022db564977e2b783d0b84753a229a77de491c

Contents?: true

Size: 913 Bytes

Versions: 14

Compression:

Stored size: 913 Bytes

Contents

# frozen_string_literal: true

module Polyphony
  # Implements general-purpose throttling
  class Throttler
    def initialize(rate)
      @rate = rate_from_argument(rate)
      @min_dt = 1.0 / @rate
      @next_time = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
    end

    def call
      now = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
      delta = @next_time - now
      Thread.current.agent.sleep(delta) if delta > 0
      yield self

      loop do
        @next_time += @min_dt
        break if @next_time > now
      end
    end
    alias_method :process, :call

    def stop
      @stop = true
    end

    private

    def rate_from_argument(arg)
      return arg if arg.is_a?(Numeric)

      if arg.is_a?(Hash)
        return 1.0 / arg[:interval] if arg[:interval]
        return arg[:rate] if arg[:rate]
      end
      raise "Invalid rate argument #{arg.inspect}"
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
polyphony-0.44.0 lib/polyphony/core/throttler.rb
polyphony-0.43.11 lib/polyphony/core/throttler.rb
polyphony-0.43.10 lib/polyphony/core/throttler.rb
polyphony-0.43.9 lib/polyphony/core/throttler.rb
polyphony-0.43.8 lib/polyphony/core/throttler.rb
polyphony-0.43.6 lib/polyphony/core/throttler.rb
polyphony-0.43.5 lib/polyphony/core/throttler.rb
polyphony-0.43.4 lib/polyphony/core/throttler.rb
polyphony-0.43.3 lib/polyphony/core/throttler.rb
polyphony-0.43.2 lib/polyphony/core/throttler.rb
polyphony-0.43.1 lib/polyphony/core/throttler.rb
polyphony-0.43 lib/polyphony/core/throttler.rb
polyphony-0.42 lib/polyphony/core/throttler.rb
polyphony-0.41 lib/polyphony/core/throttler.rb