zoukankan      html  css  js  c++  java
  • C# 监控windows服务,针对因异常停止的服务进行重启

    十年河东,十年河西,莫欺少年穷

    学无止境,精益求精

    在部署windows服务后,如果服务偶尔因系统异常停止工作,短期时间内无法找到解决方案,那么只能采用亡羊补牢的办法了,如下:

    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 System.Threading.Tasks;
    
    namespace BatteryStartServices
    {
        public partial class Service1 : ServiceBase
        {
            public Service1()
            {
                InitializeComponent();
            }
            System.Timers.Timer timer1;  //计时器
            List<string> services = new List<string>() { "BatteryCabinetService", "BatteryOtaService", "BatteryService" };
            protected override void OnStart(string[] args)
            {
                timer1 = new System.Timers.Timer();
                timer1.Interval = 10000;  //设置计时器事件间隔执行时间  每隔10秒执行一次
                timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
                timer1.Enabled = true;
            }
    
            protected override void OnStop()
            {
                timer1.Enabled = false;
            }
    
            private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                foreach(var item in services)
                {
                    ServiceController service = new ServiceController(item);
                    try
                    {
                        if (service.Status != ServiceControllerStatus.Running)
                        {
                            service.Start();
                            service.WaitForStatus(ServiceControllerStatus.Running);
    
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
               
            }
        }
    }

    除了以上程序外,我们还需要将exe文件设置为以管理员运行,如下:

     这样就有权限重启其他服务了。

    @天才卧龙的波尔克

     

  • 相关阅读:
    itextpdf 和 pdfbox 测试用例
    Java base64 编码、解码
    常用字体
    DIY 单片机 入门
    太难了。
    Java 之 native:JNI 本地方法测试实现
    Java 之 String 引用传递
    Java class 文件 方法的指令含义
    Spring学习文章链接
    数据结构_树_图_总结
  • 原文地址:https://www.cnblogs.com/chenwolong/p/14565184.html
Copyright © 2011-2022 走看看