protected override void OnStop() { if (_timer != null) { _timer.Stop(); _timer.Dispose(); LogHelpr.Info("守护服务停止"); } }
/// <summary> /// 监测应用程序运行状态 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Timer_AppSmart(object sender, System.Timers.ElapsedEventArgs e) { if (Process.GetProcessesByName(toWatchAppName).ToList().Count < 1) { LogHelpr.Info("监测到应用程序已经关闭......"); LogHelpr.Info("正在重新启动应用程序......"); AppStart(@FilePath+toWatchAppName + ".exe"); } }
protected override void OnStart(string[] args) { //服务启动时开启定时器 _timer = new System.Timers.Timer { Interval = _timerInterval, Enabled = true, AutoReset = true }; _timer.Elapsed += Timer_Elapsed; _timer.Elapsed += Timer_AppSmart; LogHelpr.Info("守护服务开启"); }
/// <summary> /// 启动服务 /// </summary> /// <param name="serviceName">要启动的服务名称</param> private void StartService(string serviceName) { try { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController service in services) { if (service.ServiceName.Trim() == serviceName.Trim()) { service.Start(); //直到服务启动 service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30)); LogHelpr.Info(string.Format("启动服务:{0}", serviceName)); } } } catch (Exception ex) { LogHelpr.Error(ex.ToString()); } }