lib/rubysermon/result_grabber.rb
d8a5adb0
 require "date"
 require "monitor"
 
 module Rubysermon
 
 	# Nastartuje nekonecny cyklus v treade, ktory si bude volat
 	# moduly (ich vysledky), tie bude ukladat do svojho hasha,
 	# pripadne vysle signal na notify.
 	#
 	class ResultGrabber
 
 		def initialize(mods, sleep)
 			@results = {}
 			@grabber_thread = nil
 
 			@running_mods = mods
 			@sleep = sleep
 
 			@monitor = Monitor.new
 		end
 
 		def run
 			@grabber_thread = Thread.new do
 				while true
 					current_time = DateTime.now()
 					@running_mods.each do |mod|
 						#$stdout.puts mod.results()
 						save_results(mod.class, current_time, mod.results())
 					end
 					sleep @sleep
 				end
 			end
 		end
 
 		def stop
 			@grabber_thread.exit()
 		end
 
 		def get_last_results
 			results = []
 			@monitor.synchronize do
 				results = get_results()
 				empty_results()
 			end
 
 			results
 		end
 
 		private
 
 		def save_results(mod_name, time, result)
 			mod_results = @results[mod_name].to_a
 
 			@monitor.synchronize do
 				#shift() and push() operations have O(1) complexity.
 				mod_results.shift()
 				mod_results.push({time: time, value: result})
 
 				@results[mod_name] = mod_results
 			end
 		end
 
 		def get_results
 			#TODO samostatny objekt vysledkov a nie pole
 			@results
 		end
 
 		def empty_results
 			@results = {}
 		end
 	end
 end