[C#]通用守护进程服务

Posted tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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);
            }
        }
    }
}

以上是关于[C#]通用守护进程服务的主要内容,如果未能解决你的问题,请参考以下文章

.NET跨平台实践:用C#开发Linux守护进程

.NET跨平台实践:用C#开发Linux守护进程(转)

.NET跨平台实践:用C#开发Linux守护进程-Daemon

守护进程与非守护进程

.NET跨平台实践:.NetCore.Net5/6 Linux守护进程设计

Windows下的通用进程守护程序(持续更新中),高仿supervisor。

(c)2006-2024 SYSTEM All Rights Reserved IT常识