Daemon Monitor Windows Services Status

來源:互聯網
上載者:User
namespace Microshaoft{    using System;    using System.Timers;    using System.Management;    using System.ServiceProcess;    using System.Diagnostics;    using System.ComponentModel;    using System.Collections.Generic;    using System.Security.Principal;    using System.Configuration.Install;    using Microshaoft;    public class SimpleService : ServiceBase //繼承於 ServiceBase    {        public const string serviceName = "ServicesDaemon";        private Timer _timer;        public static void Main(string[] args)        {            SimpleService x = new SimpleService();            int l = 0;            if (args != null)            {                l = args.Length;            }            if (l > 0) //有參數時以 console 方式運行            {                Console.Title = "serviceName";                Console.WriteLine("Run as Console");                x.OnStart(null);                Console.ReadLine();            }            else            //intallutil 成服務後            //即: 無參數時,以 Service 方式運行            {                Console.WriteLine("Run as Service");                ServiceBase.Run(x);            }        }        public SimpleService()        {            CanPauseAndContinue = true;            ServiceName = SimpleService.serviceName;        }        protected override void OnStart(string[] args)        {            Console.WriteLine(".Net Version: {0}", Environment.Version.ToString());            Console.WriteLine("Current Identity: {0}", WindowsIdentity.GetCurrent().Name);            Console.WriteLine("{0} started,at {1}", SimpleService.serviceName, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ss"));            _timer = new Timer();            _timer.Interval = 60 * 1000;            _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);            _timer.Start();            _timer_Elapsed(null, null);            //在這裡寫你的程式        }        void _timer_Elapsed(object sender, ElapsedEventArgs e)        {            _timer.Stop();            try            {                Process();            }            catch            {            }            finally            {                _timer.Start();            }        }        private void Process()        {            ManagementObjectSearcher searcher = new ManagementObjectSearcher                                                                (                                                                    "root\\CIMV2",                                                                    "SELECT * FROM Win32_Service where name like 'hello%'"                                                                );            ManagementObjectCollection moc = searcher.Get();            foreach (ManagementObject mo in moc)            {                string logMessage;                string service = null;                try                {                    service = mo["Name"].ToString();                    if (mo["State"].ToString().ToLower() != "running")                    {                        logMessage = string.Format                                                (                                                    "主機[{0}],[{1}],[{2}] 服務於[{3}]沒有運行"                                                    , Environment.MachineName                                                    , service                                                    , mo["StartMode"].ToString()                                                    , DateTime.Now                                                 );                        EventLogHelper.WriteEventLogEntry                                            (                                                this.ServiceName + " log",                                                service + " source",                                                logMessage,                                                EventLogEntryType.Error                                            );                        if (mo["StartMode"].ToString().ToLower() == "auto")                        {                            ServiceController controller = new ServiceController(service);                            if (controller.Status != ServiceControllerStatus.Running)                            {                                controller.Start();                            }                            logMessage = string.Format                                                    (                                                        "主機[{0}],[{1}],[{2}] 服務於[{3}]成功重新啟動"                                                        , Environment.MachineName                                                        , service                                                        , mo["StartMode"].ToString()                                                        , DateTime.Now                                                    );                            EventLogHelper.WriteEventLogEntry                                                (                                                    this.ServiceName + " log",                                                    service + " source",                                                    logMessage,                                                    EventLogEntryType.Information                                                );                        }                    }                }                catch (ManagementException me)                {                    logMessage = string.Format                                            (                                                "主機[{0}],[{1}],[{2}] 服務查詢發生[{3}]異常[{4}],於[{5}]"                                                , Environment.MachineName                                                , service                                                , mo["StartMode"].ToString()                                                , "ManagementException"                                                , me.ToString()                                                , DateTime.Now                                            );                    EventLogHelper.WriteEventLogEntry                                            (                                                this.ServiceName + " log",                                                service + " source",                                                logMessage,                                                EventLogEntryType.Error                                            );                }                catch (Exception e)                {                    logMessage = string.Format                                            (                                                "主機[{0}],[{1}],[{2}] 服務查詢發生[{3}]異常[{4}],於[{5}]"                                                , Environment.MachineName                                                , service                                                , mo["StartMode"].ToString()                                                , "Exception"                                                , e.ToString()                                                , DateTime.Now                                            );                    EventLogHelper.WriteEventLogEntry                                            (                                                this.ServiceName + " log",                                                service + " source",                                                logMessage, EventLogEntryType.Error                                            );                }            }        }    }    //以下就是比普通應用程式多出的 ProjectInstaller    [RunInstallerAttribute(true)]    public class ProjectInstaller : Installer    {        private ServiceInstaller serviceInstaller;        private ServiceProcessInstaller processInstaller;        public ProjectInstaller()        {            processInstaller = new ServiceProcessInstaller();            serviceInstaller = new ServiceInstaller();            // Service will run under system account            processInstaller.Account = ServiceAccount.LocalSystem;            // Service will have Start Type of Manual            serviceInstaller.StartType = ServiceStartMode.Manual;            serviceInstaller.ServiceName = SimpleService.serviceName;            Installers.Add(serviceInstaller);            Installers.Add(processInstaller);        }    }}namespace Microshaoft{    using System;    using System.Diagnostics;    class EventLogHelper    {        public static void WriteEventLogEntry                                        (                                            string logName,                                            string sourceName,                                            string logMessage,                                            EventLogEntryType logEntryType                                        )        {            if (!EventLog.SourceExists(sourceName))            {                EventLog.CreateEventSource(sourceName, logName);            }            EventLog log = new EventLog();            log.Source = sourceName;            log.WriteEntry(logMessage, logEntryType);        }    }}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.