Sha256: f175630333e3d041921b73958738e9f50dd2f299f22ad55818228d261cd71bbb

Contents?: true

Size: 913 Bytes

Versions: 32

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
      Polyphony.backend_sleep(delta) if delta > 0
      yield self

      while true
        @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

32 entries across 32 versions & 1 rubygems

Version Path
polyphony-0.79 lib/polyphony/core/throttler.rb
polyphony-0.78 lib/polyphony/core/throttler.rb
polyphony-0.77 lib/polyphony/core/throttler.rb
polyphony-0.76 lib/polyphony/core/throttler.rb
polyphony-0.75 lib/polyphony/core/throttler.rb
polyphony-0.74 lib/polyphony/core/throttler.rb
polyphony-0.73.1 lib/polyphony/core/throttler.rb
polyphony-0.73 lib/polyphony/core/throttler.rb
polyphony-0.72 lib/polyphony/core/throttler.rb
polyphony-0.71 lib/polyphony/core/throttler.rb
polyphony-0.70 lib/polyphony/core/throttler.rb
polyphony-0.69 lib/polyphony/core/throttler.rb
polyphony-0.68 lib/polyphony/core/throttler.rb
polyphony-0.67 lib/polyphony/core/throttler.rb
polyphony-0.66 lib/polyphony/core/throttler.rb
polyphony-0.65 lib/polyphony/core/throttler.rb
polyphony-0.64 lib/polyphony/core/throttler.rb
polyphony-0.63 lib/polyphony/core/throttler.rb
polyphony-0.62 lib/polyphony/core/throttler.rb
polyphony-0.61 lib/polyphony/core/throttler.rb