Sha256: e57818d1fd60fa428efa92c5761c7b2e5f459d76325ba4aad5fa4d9d77af6df4

Contents?: true

Size: 1.13 KB

Versions: 5

Compression:

Stored size: 1.13 KB

Contents

class UState::MetricThread
  # A metric thread is simple: it wraps some metric object which responds to <<,
  # and every interval seconds, calls #flush which replaces the object and calls
  # a user specified function.
 
  INTERVAL = 10
  
  attr_accessor :interval
  attr_accessor :metric

  # client = UState::Client.new
  # m = MetricThread.new Mtrc::Rate do |rate|
  #   client << rate
  # end
  #
  # loop do
  #   sleep rand
  #   m << rand
  # end
  def initialize(klass, *klass_args, &f)
    @klass = klass
    @klass_args = klass_args
    @f = f
    @interval = INTERVAL

    @metric = new_metric

    start
  end

  def <<(*a)
    @metric.<<(*a)
  end

  def new_metric
    @klass.new *@klass_args
  end

  def flush
    old, @metric = @metric, new_metric
    @f[old]
  end

  def start
    raise RuntimeError, "already running" if @runner
  
    @running = true
    @runner = Thread.new do
      while @running
        sleep @interval
        begin
          flush
        rescue Exception => e
        end
      end
      @runner = nil
    end
  end

  def stop
    stop!
    @runner.join
  end

  def stop!
    @running = false
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
ustate-client-0.0.8 lib/ustate/metric_thread.rb
ustate-client-0.0.7 lib/ustate/metric_thread.rb
ustate-client-0.0.6 lib/ustate/metric_thread.rb
ustate-client-0.0.5 lib/ustate/metric_thread.rb
ustate-client-0.0.4 lib/ustate/metric_thread.rb