Sha256: 5137929de207c3c2c2d84379724f93e2d4dce7c2f97a6e998935c5e51017ba18

Contents?: true

Size: 813 Bytes

Versions: 6

Compression:

Stored size: 813 Bytes

Contents

# frozen_string_literal: true

export_default :Throttler

class Throttler
  def initialize(rate)
    @rate = rate_from_argument(rate)
    @min_dt = 1.0 / @rate
    @last_iteration_clock = clock - @min_dt
  end

  def clock
    ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
  end

  def call(&block)
    now = clock
    dt = now - @last_iteration_clock
    if dt < @min_dt
      sleep(@min_dt - dt)
    end
    @last_iteration_clock = dt > @min_dt ? now : @last_iteration_clock + @min_dt
    block.call(self)
  end

  alias_method :process, :call

  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

6 entries across 6 versions & 1 rubygems

Version Path
polyphony-0.19 lib/polyphony/core/throttler.rb
polyphony-0.17 lib/polyphony/core/throttler.rb
polyphony-0.16 lib/polyphony/core/throttler.rb
polyphony-0.15 lib/polyphony/core/throttler.rb
polyphony-0.14 lib/polyphony/core/throttler.rb
polyphony-0.13 lib/polyphony/core/throttler.rb