public void Execute(IJobExecutionContext context) { foreach (var item in Confs) { var service = new ServiceController(item.Key); try { log.InfoFormat("{0}服务执行重启,描述:{1} 正在重启", item.Key, Confs[item.Key]); var st = Stopwatch.StartNew(); if (service.Status == ServiceControllerStatus.Running) { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped); } service.Start(); service.WaitForStatus(ServiceControllerStatus.Running); st.Stop(); log.InfoFormat("服务:{0} 描述:{1} 重启成功,耗时:{2}", item.Key, Confs[item.Key], st.ElapsedMilliseconds); } catch (Exception exception) { log.Fatal(string.Format("重启服务:{0} 重启失败!", item.Key), exception); } finally { service.Close(); } } }
public static void DoTask(CancellationTokenSource tokenSource) { Task.Factory.StartNew(() => { while (!tokenSource.IsCancellationRequested) { while (true) { try { GlobalVariable.modeLock.EnterReadLock(); if (GlobalVariable.mode == "auto") { break; } } finally { GlobalVariable.modeLock.ExitReadLock(); } Thread.Sleep(1000 * 5); } //获得服务集合 var serviceControllers = ServiceController.GetServices(); var stopAll = serviceControllers.Where(x => x.Status == ServiceControllerStatus.Stopped); Parallel.ForEach(stopAll, x => { if (!Confs.ContainsKey(x.ServiceName)) { return; } try { Log.InfoFormat("检测到服务:{0} 描述:{1} 已停止,正在重启", x.ServiceName, Confs[x.ServiceName]); var st = Stopwatch.StartNew(); x.Start(); x.WaitForStatus(ServiceControllerStatus.Running); st.Stop(); Log.InfoFormat("服务:{0} 描述:{1} 重启成功,耗时:{2}", x.ServiceName, Confs[x.ServiceName], st.ElapsedMilliseconds); } catch (InvalidOperationException exception) { Log.Fatal(string.Format("已知错误 服务:{0} 重启失败!", x.ServiceName), exception); } catch (Exception exception) { Log.Fatal(string.Format("未知错误 服务:{0} 重启失败!", x.ServiceName), exception); } }); Thread.Sleep(new TimeSpan(0, 1, 0)); } }); }