From 4ee5717b0de468c4b86c93059f9303ea703e1d5b Mon Sep 17 00:00:00 2001 From: wanghaomei Date: Wed, 12 Jul 2023 10:34:23 +0800 Subject: [PATCH] =?UTF-8?q?=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ServiceDeamon/App.config | 3 ++- ServiceDeamon/CheckServiceHelper.cs | 13 ++++++++++--- ServiceDeamon/Program.cs | 26 ++++++++++++++++++++------ ServiceDeamon/ServiceDeamon.csproj | 2 ++ 4 files changed, 34 insertions(+), 10 deletions(-) diff --git a/ServiceDeamon/App.config b/ServiceDeamon/App.config index 8780b642..75622970 100644 --- a/ServiceDeamon/App.config +++ b/ServiceDeamon/App.config @@ -1,6 +1,7 @@  - + + \ No newline at end of file diff --git a/ServiceDeamon/CheckServiceHelper.cs b/ServiceDeamon/CheckServiceHelper.cs index 9b489d19..0ba70891 100644 --- a/ServiceDeamon/CheckServiceHelper.cs +++ b/ServiceDeamon/CheckServiceHelper.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Configuration; using System.Linq; using System.ServiceProcess; using System.Text; @@ -11,18 +12,24 @@ namespace ServiceDeamon { private static ServiceController servCtl; + private static string ServName = ConfigurationManager.AppSettings["ServiceName"]; - public static void CheckStatus(string servName) + public static void CheckStatus() { - if (servCtl == null || servCtl.ServiceName != servName) + if (servCtl == null || servCtl.ServiceName != ServName) { - servCtl = new ServiceController(servName); + servCtl = new ServiceController(ServName); } + Console.WriteLine($"服务 {ServName} 的当前状态:{servCtl.Status}"); + if (servCtl != null && servCtl.Status == ServiceControllerStatus.Stopped) { + Console.WriteLine($"服务已停止,自动启动:{ServName}"); servCtl.Start(); } + + //Console.WriteLine("CheckStatus"); } } } diff --git a/ServiceDeamon/Program.cs b/ServiceDeamon/Program.cs index 064ff175..b4760fc8 100644 --- a/ServiceDeamon/Program.cs +++ b/ServiceDeamon/Program.cs @@ -2,12 +2,26 @@ using System.Configuration; using System.ServiceProcess; -var servName = ConfigurationManager.AppSettings["ServiceName"]; +public class Program +{ + private static Timer timer; -//Timer t = new System.Threading.Timer((sta) => -//{ -// CheckServiceHelper.CheckStatus(servName); -//}); + private static int CheckInteval = Convert.ToInt32(ConfigurationManager.AppSettings["CheckInteval"]); -//t.Change(1000,) + public static void Main(string[] args) + { + timer = new Timer(new TimerCallback(CheckSta)); + timer.Change(CheckInteval, Timeout.Infinite); + + + Console.Read(); + } + + private static void CheckSta(object sta) + { + CheckServiceHelper.CheckStatus(); + + timer.Change(CheckInteval, Timeout.Infinite); + } +} diff --git a/ServiceDeamon/ServiceDeamon.csproj b/ServiceDeamon/ServiceDeamon.csproj index 9af9c439..ffa42eaf 100644 --- a/ServiceDeamon/ServiceDeamon.csproj +++ b/ServiceDeamon/ServiceDeamon.csproj @@ -8,7 +8,9 @@ + +