• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# 监控windows服务,针对因异常停止的服务进行重启

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

学无止境,精益求精

在部署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文件设置为以管理员运行,如下:

 

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

@天才卧龙的波尔克

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#MongoDB--时区问题(差了8小时)发布时间:2022-07-13
下一篇:
C#开发系列(三)发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap