C# 應用ServiceController控制自訂windows service

來源:互聯網
上載者:User

    在C#中,windows service專案編譯部署後,可以通過ServiceController在外部對此Windows service加以控制:可以停止,可以重新啟動等,也可以傳遞特定的指令給windows service,

windows service接收到這些指令後,可以根據定義做些特定的事情。

using System;using System.ServiceProcess;using System.Text;using System.IO;namespace myScheduledJob{    public partial class ScheduledJob : ServiceBase    {        public ScheduledJob()        {            InitializeComponent();        }        protected override void OnStart(string[] args)        {            writeLog("windows service Started  at " + DateTime.Now.ToString());        }        protected override void OnStop()        {            writeLog("windows service Stoped  at " + DateTime.Now.ToString());        }        /// <summary>        /// 此方法用於接收特定的Command        /// </summary>        /// <param name="command">command指令</param>        protected override void OnCustomeCommand(int command)        {            if (command >= 128 && command <= 255)            {                switch (command)                {                    case 140:                        {                            writeLog("windows service received command" + command);                        }                        break;                    case 141:                        {                            writeLog("windows service received command" + command);                        }                        break;                }            }            else            {                writeLog("service command is invalid");            }        }        private void writeLog(string text)        {            Monitor.Enter(lockObject);            System.IO.StreamWriter sw = null;            try            {                string logPath = systemPath + @"\" + logForderPath;                string logFile = logPath + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt";                string fullText = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\t" + text;                checkFile(logFile);                sw = System.IO.File.AppendText(logFile);                sw.WriteLine(fullText);                sw.Flush();                sw.Close();            }            finally            {                Monitor.Exit(lockObject);            }        }        private void checkFile(string fileName)        {            if (!System.IO.File.Exists(fileName))            {                System.IO.StreamWriter sw = System.IO.File.CreateText(fileName);                sw.Close();            }        }    }}

需要注意的是:Command指令接收的參數限制:int, 128-255.

接下來通過如下測試代碼示範上述內容:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;using System.Reflection;using System.Threading;using System.ServiceProcess;namespace fileSystemWatcherDemo{    class Program    {        static void Main(string[] args)        {            Command();        }        private static void Command()        {            Console.WriteLine("Please input the command:");            string cmd = Console.ReadLine();            Console.WriteLine("You have Input the " + cmd);            if (cmd != "q")            {                sendCommandToService(cmd);                Command();            }        }        private static void sendCommandToService(string cmd)        {            try            {                ServiceController sc = new ServiceController();                sc.MachineName = Environment.MachineName;                sc.ServiceName = "myScheduledJob";                sc.ExecuteCommand(Convert.ToInt32(cmd)); //使用此命令,Service必須是Started 狀態,cmd必須是128-255之間整數            }            catch (Exception ex)            {                Console.WriteLine(ex.InnerException);            }            //利用ServiceController可以控制Windows Service
//if (sc.Status == ServiceControllerStatus.Stopped) // sc.Start(); //else // sc.Stop(); } }}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.