Sha256: 8ddde90003e5f7c6d455bb75f0dbbc15cd3c79e35de163e6a79a195a47052647

Contents?: true

Size: 639 Bytes

Versions: 7

Compression:

Stored size: 639 Bytes

Contents

# frozen_string_literal: true

export_default :Throttler

# Implements general-purpose throttling
class Throttler
  def initialize(rate)
    @rate = rate_from_argument(rate)
    @min_dt = 1.0 / @rate
  end

  def call(&block)
    @timer ||= Gyro::Timer.new(0, @min_dt)
    @timer.await
    block.call(self)
  end
  alias_method :process, :call

  def stop
    @timer&.stop
  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

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
polyphony-0.36 lib/polyphony/core/throttler.rb
polyphony-0.34 lib/polyphony/core/throttler.rb
polyphony-0.33 lib/polyphony/core/throttler.rb
polyphony-0.32 lib/polyphony/core/throttler.rb
polyphony-0.31 lib/polyphony/core/throttler.rb
polyphony-0.30 lib/polyphony/core/throttler.rb
polyphony-0.29 lib/polyphony/core/throttler.rb