1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
class Riemann::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 = Riemann::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
|