class Datadog::Statsd::Timer

Public Class Methods

new(interval, &callback) click to toggle source
# File lib/datadog/statsd/timer.rb, line 6
def initialize(interval, &callback)
  @mx = Mutex.new
  @cv = ConditionVariable.new
  @interval = interval
  @callback = callback
  @stop = true
  @thread = nil
end

Public Instance Methods

start() click to toggle source
# File lib/datadog/statsd/timer.rb, line 15
def start
  return unless stop?

  @stop = false
  @thread = Thread.new do
    last_execution_time = current_time
    @mx.synchronize do
      until @stop
        timeout = @interval - (current_time - last_execution_time)
        @cv.wait(@mx, timeout > 0 ? timeout : 0)
        last_execution_time = current_time
        @callback.call
      end
    end
  end
  @thread.name = 'Statsd Timer' unless Gem::Version.new(RUBY_VERSION) < Gem::Version.new('2.3')
end
stop() click to toggle source
# File lib/datadog/statsd/timer.rb, line 33
def stop
  return if @thread.nil?

  @stop = true
  @mx.synchronize do
    @cv.signal
  end
  @thread.join
  @thread = nil
end
stop?() click to toggle source
# File lib/datadog/statsd/timer.rb, line 44
def stop?
  @thread.nil? || @thread.stop?
end

Private Instance Methods

current_time() click to toggle source
# File lib/datadog/statsd/timer.rb, line 51
def current_time
  Process.clock_gettime(Process::CLOCK_MONOTONIC)
end