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

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
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 @   人生为卒  阅读(75)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示