首页 > 系统相关 >C# 检测并重启windows服务,IIS应用池

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

时间:2024-05-31 14:56:55浏览次数:11  
标签:log IIS C# 重启 windows ServiceName ex sc string

 

 

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
    }
}

  

标签:log,IIS,C#,重启,windows,ServiceName,ex,sc,string
From: https://www.cnblogs.com/lhlong/p/18224583

相关文章

  • 2.4G讲解(BasicMode)
    BASIC模式讲解下方代码实现基于basic模式下一端发送数据,另一端接收数据并返回数据的双向传输。RF_PHY.c工程替换即可使用,注意未定义的tmos任务自行定义#include"CONFIG.h"#include"RF_PHY.h"#defineRF_AUTO_MODE_EXAM0#definerxmode1uint8_ttaskID;uint8_t......
  • 大模型应用之基于Langchain的测试用例生成
    一用例生成实践效果在组内的日常工作安排中,持续优化测试技术、提高测试效率始终是重点任务。近期,我们在探索实践使用大模型生成测试用例,期望能够借助其强大的自然语言处理能力,自动化地生成更全面和高质量的测试用例。当前,公司已经普及使用JoyCoder,我们可以拷贝相关需求及设计文......
  • 【使用技巧】CodeDecom.exe批量反编译JAR包+Beyond Compare对比
    使用工具进行批量反编译+差异对比,检查确认补丁变更D:\tmp\test\CodeDecom>CodeDecom.exe source D:\tmp\test\jarForder  D:\tmp\test\codeForder......
  • Ubuntu上使用QT creator运行cuda程序
    突发奇想想尝试一下QT界面中使用CUDA加速过的程序,然后查了一下资料,总结一下有以下几点吧1、CUDA配置全部放在.pro文件中2、main.cpp为主函数使用g++编译3、kernel.cu为核函数使用nvcc编译不多说上代码以下为main.cpp代码   #include<QtCore/QCoreApplication>       ......
  • ChaosBlade混沌测试实践
    !https://zhuanlan.zhihu.com/p/700914220ChaosBlade:一个简单易用且功能强大的混沌实验实施工具官方仓库:https://github.com/chaosblade-io/chaosblade1.项目介绍ChaosBlade是阿里巴巴开源的一款遵循混沌工程原理和混沌实验模型的实验注入工具,帮助企业提升分布式系统的容......
  • C. Tenzing and Balls
    链接:https://codeforces.com/problemset/problem/1842/Corhttps://www.luogu.com.cn/problem/CF1842C大概的思路就是利用dp[i]记录前i个数据最多消掉的数字个数,然后对∀j:a[i]==a[j]&&j<i进行dp[i]=dp[j-1]+i-j+1的递推优化:代码:#define_CRT_SECURE_NO_WARNI......
  • Введение в CAN-шину
    CAN—этоаббревиатурасетиконтроллеров(далееCAN).ЭтомеждународныйстандартпоследовательнойсвязиISO*1,предназначенныйдлярешениясложны......
  • 两台windowserver服务器配置Redis哨兵集群
    十年河东,十年河西,莫欺少年穷学无止境,精益求精redis下载地址:https://github.com/tporadowski/redis/releases 这里选择压缩版,不选择安装版1、集群环境 主机master:局域网IP  172.27.40.27从机slave:局域网IP  172.27.40.29 2、修改主从相关配置-两台服务器均需修改......
  • 【故障识别】基于CNN-SVM卷积神经网络结合支持向量机的数据分类预测研究(Matlab代码实
    ......
  • AWC6.3.8 开发环境搭建(虚拟机中)
    前提安装完毕awc,并且能够正常访问在配置nodejs环境变量添加NODE_PATH下载vscode并安装(也可以用其他工具)拷贝stageC:\Siemens\Teamcenter14\aws2\stage=>C:\dev\stage修改initenv.cmd,增加两行运行在开发工具中cdc:/dev/stage#执行initenv.cmd.\init......