zoukankan      html  css  js  c++  java
  • [C#]通用守护进程服务

    摘要

    很多情况下,都会使用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);
                }
            }
        }
    }
  • 相关阅读:
    荷兰国旗问题
    读取文件中数据到数组
    从五个球中选出3个枚举的简单运用
    搜索算法总结
    匿名对象
    欧几里得距离C++代码实现
    用递归法吧字符串S倒序
    利用系统来完成十进制,十六进制,八进制的转换
    DBHelper 使用的是存储过程
    DBHelper的一个小例子
  • 原文地址:https://www.cnblogs.com/wolf-sun/p/5911986.html
Copyright © 2011-2022 走看看