Class: UState::MetricThread

Inherits:
Object
  • Object
show all
Defined in:
lib/ustate/metric_thread.rb

Constant Summary collapse

INTERVAL =

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.

10

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, *klass_args, &f) ⇒ MetricThread

client = UState::Client.new m = MetricThread.new Mtrc::Rate do |rate|

client << rate

end

loop do

sleep rand
m << rand

end



20
21
22
23
24
25
26
27
28
29
# File 'lib/ustate/metric_thread.rb', line 20

def initialize(klass, *klass_args, &f)
  @klass = klass
  @klass_args = klass_args
  @f = f
  @interval = INTERVAL

  @metric = new_metric

  start
end

Instance Attribute Details

#intervalObject

Returns the value of attribute interval.



8
9
10
# File 'lib/ustate/metric_thread.rb', line 8

def interval
  @interval
end

#metricObject

Returns the value of attribute metric.



9
10
11
# File 'lib/ustate/metric_thread.rb', line 9

def metric
  @metric
end

Instance Method Details

#<<(*a) ⇒ Object



31
32
33
# File 'lib/ustate/metric_thread.rb', line 31

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

#flushObject



39
40
41
42
# File 'lib/ustate/metric_thread.rb', line 39

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

#new_metricObject



35
36
37
# File 'lib/ustate/metric_thread.rb', line 35

def new_metric
  @klass.new *@klass_args
end

#startObject

Raises:

  • (RuntimeError)


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ustate/metric_thread.rb', line 44

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

#stopObject



60
61
62
63
# File 'lib/ustate/metric_thread.rb', line 60

def stop
  stop!
  @runner.join
end

#stop!Object



65
66
67
# File 'lib/ustate/metric_thread.rb', line 65

def stop!
  @running = false
end