摘要
很多情况下,都会使用windows服务做一些任务,但总会有一些异常,导致服务停止。这个时候,开发人员又不能立马解决问题,所以做一个守护者服务还是很有必要的。当检测到服务停止了,重启一下服务,等开发人员到位了,再排查错误日志。
代码
app.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <appSettings> <!--要守护的服务的服务名称--> <add key="toWatchServiceName" value=""/> <!--守护服务的名称--> <add key="serviceName" value="邮件提醒服务守护服务"/> <!--每1分钟检查一次 以秒为单位--> <add key="timerInterval" value="60"/> </appSettings> </configuration>
服务
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; namespace WindowsService.Watch { partial class ServiceWather : ServiceBase { private static string currentExePath = string.Empty; public ServiceWather() { InitializeComponent(); currentExePath = AppDomain.CurrentDomain.BaseDirectory; } /// <summary> /// 检查间隔 /// </summary> private static readonly int _timerInterval = Convert.ToInt32(ConfigurationManager.AppSettings["timerInterval"]) * 1000; /// <summary> /// 要守护的服务名 /// </summary> private static readonly string toWatchServiceName = ConfigurationManager.AppSettings["toWatchServiceName"]; private System.Timers.Timer _timer; protected override void OnStart(string[] args) { //服务启动时开启定时器 _timer = new System.Timers.Timer(); _timer.Interval = _timerInterval; _timer.Enabled = true; _timer.AutoReset = true; _timer.Elapsed += _timer_Elapsed; LogHelper.WriteLog(currentExePath, "守护服务开启"); } void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { //如果服务状态为停止,则重新启动服务 if (!CheckSericeStart(toWatchServiceName)) { StartService(toWatchServiceName); } } protected override void OnStop() { if (_timer != null) { _timer.Stop(); _timer.Dispose(); LogHelper.WriteLog(currentExePath, "守护服务停止"); } } /// <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)); LogHelper.WriteLog(currentExePath, string.Format("启动服务:{0}", serviceName)); } } } catch (Exception ex) { LogHelper.WriteLog(currentExePath, ex); } } private bool CheckSericeStart(string serviceName) { bool result = true; try { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController service in services) { if (service.ServiceName.Trim() == serviceName.Trim()) { if ((service.Status == ServiceControllerStatus.Stopped) || (service.Status == ServiceControllerStatus.StopPending)) { result = false; } } } } catch (Exception ex) { LogHelper.WriteLog(currentExePath, ex); } return result; } /// <summary> /// 停止 /// </summary> /// <param name="serviceName"></param> private void StopService(string serviceName) { try { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController service in services) { if (service.ServiceName.Trim() == serviceName.Trim()) { service.Stop(); //直到服务停止 service.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 30)); LogHelper.WriteLog(currentExePath, string.Format("启动服务:{0}", serviceName)); } } } catch (Exception ex) { LogHelper.WriteLog(currentExePath, ex); } } } }
时间: 2024-10-06 00:20:23