1313
1414
1515class ProcessSensor (Plugin ):
16- def __init__ (self ,** kwargs ):
16+ PROCESS_LIST_CLEANUP_TICKS = 100
17+
18+ def __init__ (self , ** kwargs ):
1719 super (ProcessSensor ,self ).__init__ (** kwargs )
1820 # there will be two parts of the returned value, one will be text and other graph
1921 # there can be many text (key,value) pairs to display corresponding to each key
@@ -23,7 +25,8 @@ def __init__(self,**kwargs):
2325 self ._currentSystemUser = getpass .getuser ()
2426 self ._logger = logging .getLogger (__name__ )
2527 # processes once retrieved from psutil are stored in a list to make cpu percentage measurement possible
26- self ._process_list = []
28+ self ._process_list = {}
29+ self ._tick = 0
2730
2831 def format_time (self , d ):
2932 ret = '{0} day{1} ' .format (d .days , ' s' [d .days > 1 ]) if d .days else ''
@@ -94,11 +97,19 @@ def update(self):
9497 self .currentValue ['text' ]['running_processes' ] = str (proc_count )
9598 self .currentValue ['text' ]['running_threads' ] = str (thread_count )
9699
100+ self .tick (proc_info_list )
101+
102+ def tick (self , proc_info_list ):
103+ self ._tick = (self ._tick + 1 ) % ProcessSensor .PROCESS_LIST_CLEANUP_TICKS
104+ if self ._tick == 0 :
105+ self ._process_list = {key : value for (key , value ) in self ._process_list .items () if key in [y ['id' ] for y in proc_info_list ]}
106+
97107 def retrieve_process_by_pid (self , pid ):
98- found_processes = [x for x in self ._process_list if x .pid == pid ]
99- process = found_processes [0 ] if len (found_processes ) > 0 else psutil .Process (pid )
100- if not found_processes and process :
101- self ._process_list .append (process )
108+ try :
109+ process = self ._process_list [pid ]
110+ except KeyError :
111+ process = psutil .Process (pid )
112+ self ._process_list [pid ] = process
102113 return process
103114
104115
0 commit comments