C# 检测并重启windows服务,IIS应用池

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using log4net;
using System.Timers;

using System.Configuration;

namespace RfidDAWatcher
{
    public partial class WatchService : ServiceBase
    {
        private ILog log = LogManager.GetLogger(typeof(WatchService));
        private   static Timer tmrWatchTimer = new Timer();

        /// <summary>
        /// 重启间隔小时数
        /// </summary>
        int ReStartHour = 0;

        /// <summary>
        /// 执行间隔
        /// </summary>
        string watchInterval = "";
        /// <summary>
        /// 是否需要重启服务
        /// </summary>
        DateTime LastReStartdt = DateTime.Now;



        public WatchService()
        {
            InitializeComponent();

            watchInterval = ConfigurationManager.AppSettings["WatchInterval"];

            log.Error("服务器启动成功");
            try
            {
                ReStartHour = Convert.ToInt16(ConfigurationManager.AppSettings["AddHours"]);
            }
            catch (Exception)
            {

                ReStartHour = 0;
            }


            tmrWatchTimer.Interval = int.Parse(watchInterval); 
            tmrWatchTimer.Elapsed += new ElapsedEventHandler(tmrWatchTimer_Elapsed);
            tmrWatchTimer.Start();
            tmrWatchTimer.Enabled = false;


            log.Error("服务器启动成功2");
        }
         
        protected override void OnStart(string[] args)
        {
            //监视进程,监视数据库标志位

            tmrWatchTimer.Enabled = true;
            log.Error("服务器启动成功3");
        }

        protected override void OnStop()
        {
            tmrWatchTimer.Enabled = false;
        }


        /// <summary>
        /// 启动方法
        /// </summary>
        public void ExcueStart()
        {
            // TODO: 在此处添加代码以启动服务。
            //线程中启动Netty
            log.ErrorFormat("服务开启,时间:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            //RunServer.zhuce();
            OnStart(null);
            log.ErrorFormat("服务开启成功,时间:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }


        /// <summary>
        /// 启动方法
        /// </summary>
        public void ExcueStop()
        {
            // TODO: 在此处添加代码以启动服务。
            //线程中启动Netty
            log.ErrorFormat("服务开启,时间:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            //RunServer.zhuce();
            OnStop();
            log.ErrorFormat("服务开启成功,时间:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }


        /// <summary>
        /// 定时器执行代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmrWatchTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            tmrWatchTimer.Enabled = false;
            try
            { 
                /// <summary>
                /// 是否需要重启服务
                /// </summary>
                bool isReStart = false;

                ///间隔时间大于0,并且已经到了需要重启的时间
                if (ReStartHour > 0)
                {
                    ///判断是否需要重启
                    if (LastReStartdt < DateTime.Now.AddMinutes(-ReStartHour))
                    {
                        LastReStartdt = DateTime.Now;
                        isReStart = true;
                        log.Error(string.Format("Service ReStart datetime is {0} !!", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                    }
                }



                ReStartWinServerMain(isReStart);

                ReStartIISServerMain(isReStart);


            }
            catch (Exception ex)
            {
                log.ErrorFormat(ex.StackTrace);
            }
            tmrWatchTimer.Enabled = true;
        }



        #region 重启windows服务

        /// <summary>
        /// 重启windows服务
        /// </summary>
        /// <param name="isReStart">是否需要重启服务,无论服务当前是什么状态</param>
        public void ReStartWinServerMain(bool isReStart)
        { 
            try
            {

                string ServiceName = string.Empty;
                for (int i = 0; i < 99; i++)
                {
                    string Servicekey = string.Format("WinService{0}", i + 1);
                    try
                    {

                        ServiceName = ConfigurationManager.AppSettings[Servicekey];


                        ReStartWinServer(ServiceName, isReStart);
                    }
                    catch (Exception ex)
                    {
                        log.Error($"{ServiceName}:启动异常:{ex.Message}》{ex.StackTrace}");
                        continue;
                    }
                    if (string.IsNullOrEmpty(ServiceName)) continue;

                }
            }
            catch (Exception ex)
            {
                log.Error($"{ServiceName}:启动异常:{ex.Message}》{ex.StackTrace}");
            }
        }

        /// <summary>
        /// 检测Windows服务,如果已停止则进行重启
        /// </summary>
        /// <param name="ServiceName">服务名称</param>
        /// <param name="isReStart">是否需要重启,无论服务当前是什么状态</param>
        public void ReStartWinServer(string ServiceName, bool isReStart)
        {
            try
            {
                if (string.IsNullOrEmpty(ServiceName)) return;

                ServiceController sc = SearchService(ServiceName);

                if (sc != null)
                {

                    ///判断是否需要重启
                    if (isReStart)
                    {

                        if (sc.Status == ServiceControllerStatus.Stopped)
                        {
                            sc.Start();
                        }
                        else if (sc.Status == ServiceControllerStatus.Running)
                        {
                            sc.Stop();

                            log.DebugFormat("WinService  {0} STOP Succues !!", sc.ServiceName);
                            sc.Start();
                        }

                        log.DebugFormat("WinService {0} Restart Succues !!", sc.ServiceName);
                    }


                    log.DebugFormat("WinService {0} status is {1} !!", sc.ServiceName, sc.Status.ToString());
                    if (sc.Status == ServiceControllerStatus.Stopped)
                    {
                        sc.Start();
                        log.DebugFormat("WinService {0} Restart Succues !!", sc.ServiceName);
                    }
                    else if (sc.Status == ServiceControllerStatus.Running)
                    {

                        //服务处于运行中检测是否正常启动 
                        //if (!"999".Equals(tmp))
                        //{
                        //    sc.Stop();
                        //    sc.Start();
                        //}
                    }
                }
                else
                {
                    log.ErrorFormat("WinService {0} not exists!!", ServiceName);
                }

            }
            catch (Exception)
            {

                throw;
            }
        }


        /// <summary>
        /// 遍历服务,得到对象
        /// </summary>
        /// <param name="servName"></param>
        /// <returns></returns>
        private ServiceController SearchService(string servName)
        {
            ServiceController[] svcs = ServiceController.GetServices();
            foreach (ServiceController svc in svcs)
            {
                if (svc.ServiceName.Equals(servName))
                    return svc;
            }
            return null;
        }


        #endregion

        #region 重启IIS应用池

        /// <summary>
        /// 重启IIS应用池
        /// </summary>
        /// <param name="isReStart">是否需要重启,无论服务当前是什么状态</param>
        public void ReStartIISServerMain(bool isReStart)
        {
            string ServiceName = string.Empty;
            try
            {
                for (int i = 0; i < 99; i++)
                {
                    string Servicekey = string.Format("IISService{0}", i + 1);
                    try
                    {

                        ServiceName = ConfigurationManager.AppSettings[Servicekey];

                        ReStartIISServer(ServiceName, isReStart);
                    }
                    catch (Exception ex)
                    {
                        log.Error($"{ServiceName}:启动异常:{ex.Message}》{ex.StackTrace}");
                        continue;
                    }
                    if (string.IsNullOrEmpty(ServiceName)) continue;

                }
            }
            catch (Exception ex)
            {
                log.Error($"{ServiceName}:启动异常:{ex.Message}》{ex.StackTrace}");
            }
        }


        /// <summary>
        /// 检测IIS应用池,如果已停止则进行重启
        /// </summary>
        /// <param name="ServiceName"></param>
        /// <param name="isReStart">是否需要重启,无论服务当前是什么状态</param>
        public void ReStartIISServer(string ServiceName, bool isReStart)
        {
            try
            {

                if (string.IsNullOrEmpty(ServiceName)) return;

                Microsoft.Web.Administration.ApplicationPool sc = SearchIISService(ServiceName);


                if (sc != null)
                {


                    ///判断是否需要重启
                    if (isReStart)
                    {

                        if (sc.State == Microsoft.Web.Administration.ObjectState.Stopped)
                        {
                            sc.Start();
                        }
                        else if (sc.State == Microsoft.Web.Administration.ObjectState.Started)
                        {
                            sc.Stop();

                            log.DebugFormat("IISService  {0} STOP Succues !!", sc.Name);
                            sc.Start();
                        }

                        log.DebugFormat("IISService {0} Restart Succues !!", sc.Name);
                    }



                    log.DebugFormat("IISService {0} status is {1} !!", sc.Name, sc.State.ToString());
                    if (sc.State == Microsoft.Web.Administration.ObjectState.Stopped)
                    {
                        sc.Start();
                        log.DebugFormat("IISService {0} Restart Succues !!", sc.Name);
                    }
                    else if (sc.State == Microsoft.Web.Administration.ObjectState.Started)
                    {

                        //服务处于运行中检测是否正常启动 
                        //if (!"999".Equals(tmp))
                        //{
                        //    sc.Stop();
                        //    sc.Start();
                        //}
                    }
                }
                else
                {
                    log.ErrorFormat("IISService {0} not exists!!", ServiceName);
                }

            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 遍历IIS应用池服务,得到对象
        /// </summary>
        /// <param name="servName">IIS应用名称</param>
        /// <returns></returns>
        private Microsoft.Web.Administration.ApplicationPool SearchIISService(string servName)
        {
            try
            {

                var manager = new Microsoft.Web.Administration.ServerManager();
                var Pools = manager.ApplicationPools;

                var Pool = Pools.FirstOrDefault(a => a.Name == servName);
                return Pool;
            }
            catch (Exception)
            {

                throw;
            }
        }

        #endregion
    }
}

  

posted @ 2024-05-31 14:44  人生为卒  阅读(18)  评论(0编辑  收藏  举报