Class: Datadog::Statsd::Timer

Inherits:
Object
  • Object
show all
Defined in:
lib/datadog/statsd/timer.rb

Instance Method Summary collapse

Constructor Details

#initialize(interval, &callback) ⇒ Timer

Returns a new instance of Timer.



6
7
8
9
10
11
12
13
# 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

Instance Method Details

#startObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 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

#stopObject



33
34
35
36
37
38
39
40
41
42
# 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?Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/datadog/statsd/timer.rb', line 44

def stop?
  @thread.nil? || @thread.stop?
end