Sha256: cf34803632db34e7a251677480b9f27851815190fa7e6d22a4b524bd03262814

Contents?: true

Size: 1.6 KB

Versions: 25

Compression:

Stored size: 1.6 KB

Contents

# frozen_string_literal: true

module Polyphony
  # Implements general-purpose throttling
  class Throttler

    # Initializes a throttler instance with the given rate.
    #
    # @param rate [Number] throttler rate in times per second
    def initialize(rate)
      @rate = rate_from_argument(rate)
      @min_dt = 1.0 / @rate
      @next_time = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
    end

    # call-seq:
    #   throttler.call { ... }
    #   throttler.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.
    #
    # @return [any] given block's return value
    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
    alias_method :process, :call

    private

    # Converts the given argument to a rate. If a hash is given, the throttler's
    # rate is computed from the value of either the `:interval` or `:rate` keys.
    #
    # @param arg [Number, Hash] rate argument
    # @return [Number] rate in times per second
    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

25 entries across 25 versions & 1 rubygems

Version Path
polyphony-0.99.4 lib/polyphony/core/throttler.rb
polyphony-0.99.3 lib/polyphony/core/throttler.rb
polyphony-0.99.2 lib/polyphony/core/throttler.rb
polyphony-0.99.1 lib/polyphony/core/throttler.rb
polyphony-0.99 lib/polyphony/core/throttler.rb
polyphony-0.98 lib/polyphony/core/throttler.rb
polyphony-0.97 lib/polyphony/core/throttler.rb
polyphony-0.96 lib/polyphony/core/throttler.rb
polyphony-0.95 lib/polyphony/core/throttler.rb
polyphony-0.94 lib/polyphony/core/throttler.rb
polyphony-0.93 lib/polyphony/core/throttler.rb
polyphony-0.92 lib/polyphony/core/throttler.rb
polyphony-0.91 lib/polyphony/core/throttler.rb
polyphony-0.90 lib/polyphony/core/throttler.rb
polyphony-0.89 lib/polyphony/core/throttler.rb
polyphony-0.87 lib/polyphony/core/throttler.rb
polyphony-0.86 lib/polyphony/core/throttler.rb
polyphony-0.85 lib/polyphony/core/throttler.rb
polyphony-0.84.1 lib/polyphony/core/throttler.rb
polyphony-0.84 lib/polyphony/core/throttler.rb