public void Start(MonitoredServices serviceCollection) { if (_processingThread != null && _processingThread.ThreadState == ThreadState.Running) { _log.Error("Cannot start, thread still running!"); State = ServiceMonitorState.Doomed; return; } State = ServiceMonitorState.Starting; _services = new List <ServiceInfo>(); foreach (var svc in serviceCollection) { var s = svc as MonitoredService; var installCmd = string.Empty; if (!string.IsNullOrEmpty(s.InstallCommandLine)) { installCmd = s.InstallCommandLine; } else if (!string.IsNullOrEmpty(s.ServiceExecutablePath)) { //topshelf service. install with 'install' param. installCmd = $"{s.ServiceExecutablePath} install -servicename:{s.ServiceName} --autostart"; } _services.Add(new ServiceInfo { ServiceName = s.ServiceName, InstallCommandLine = installCmd, MonitorInterval = s.CheckFrequencyValue, NextCheck = DateTime.Now.AddSeconds(s.CheckFrequencyValue) }); } _processingThread = new Thread(new ThreadStart(MonitorServices)); _processingThread.Start(); }
//Main thread method public void MonitorServices() { State = ServiceMonitorState.Monitoring; try { while (State == ServiceMonitorState.Monitoring) { var servicesToCheck = _services.Where(s => s.NextCheck <= DateTime.Now); if (servicesToCheck.Any()) { foreach (var svc in servicesToCheck) { //ensure we stop soon as if requested. if (State != ServiceMonitorState.Monitoring) { continue; } CheckService(svc); svc.NextCheck = DateTime.Now.AddSeconds(svc.MonitorInterval); } } var nextCheck = servicesToCheck.OrderBy(s => s.NextCheck).FirstOrDefault()?.NextCheck; //sleep for a short while to avoid eating CPU.... Thread.Sleep(500); }//Main While loop. //If we've come out of this, then we've stopped. State = ServiceMonitorState.Stopped; } catch (Exception ex) { State = ServiceMonitorState.Doomed; _log.Error($"exception raised While Monitoring! - {ex.Message}"); } }
public ServiceMonitorStateEventArgs(ServiceMonitorState state) { State = state; }
public void Stop() { State = ServiceMonitorState.Stopping; }