c#之添加window服務(定時任務)


本文講述使用window服務創建定時任務 

 

1.如圖,新建項目,windows桌面->windows服務

 

2.如圖,右鍵,添加安裝程序

 

 

3.在下圖安裝程序 serviceInstaller1 上右鍵,修改serviceName和Description

 

4.如圖,在 serviceProcessInstaller 上右鍵,修改 Account 為 LocalSystem 

 

 5.在Service1中 添加代碼

 public partial class Service1 : ServiceBase
    {
        //記錄到event log中,地址是 C:\Windows\System32\winevt\Logs (雙擊查看即可,文件名為MyNewLog)
        private static EventLog eventLog1;
        private int eventId = 1;

        public Service1()
        {
            InitializeComponent();

            eventLog1 = new System.Diagnostics.EventLog();
            if (!System.Diagnostics.EventLog.SourceExists("MySource"))
            {
                System.Diagnostics.EventLog.CreateEventSource(
                    "MySource", "MyNewLog");
            }
            eventLog1.Source = "MySource";
            eventLog1.Log = "MyNewLog";
        }

        /// <summary>
        /// 啟動服務
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            eventLog1.WriteEntry("In OnStart.");
            log("In OnStart.");

            // Set up a timer that triggers every minute. 設置定時器
            Timer timer = new Timer();
            timer.Interval = 60000; // 60 seconds 60秒執行一次
            timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
            timer.Start();
        }

        /// <summary>
        /// 停止服務
        /// </summary>
        protected override void OnStop()
        {
            eventLog1.WriteEntry("In OnStop.");
            log("In OnStop.");
        }

        /// <summary>
        /// 繼續服務
        /// </summary>
        protected override void OnContinue()
        {
            eventLog1.WriteEntry("In OnContinue.");
            log("In OnContinue.");
        }

        /// <summary>
        /// 定時器中定時執行的任務
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public void OnTimer(object sender, ElapsedEventArgs args)
        {
            // TODO: Insert monitoring activities here.
            eventLog1.WriteEntry("Monitoring the System", EventLogEntryType.Information, eventId++);
            log("the timer");
        }



        /// <summary>
        /// 記錄到指定路徑:D:\log.txt
        /// </summary>
        /// <param name="message"></param>
        private static void log(string message)
        {
            using (FileStream stream = new FileStream("D:\\log.txt", FileMode.Append))
                using(StreamWriter writer=new StreamWriter(stream))
            {
                writer.WriteLine($"{DateTime.Now}:{message}");
            }
        }

    }

 

結構如圖:

 

 6.右鍵生成解決方案

 

 7.打開項目,復制bin目錄到C盤下新建的 windowServiceTest 文件夾的 windowService_Hello文件夾下,另外復制 C:\Windows\Microsoft.NET\Framework\v4.0.30319 下的 InstallUtil.exe 到 windowServiceTest 文件夾下;如圖

 

 

 

8.安裝服務

 打開cmd (以管理員身份),並且進入windowServiceTest  文件夾下

  安裝服務:

InstallUtil.exe  C:\windowServiceTest\windowService_Hello\bin\Debug\WindowService_HelloWorld.exe

效果圖:

 

 9.打開服務管理器,啟動MyService服務,並且等待幾分鍾,然后卸載服務

卸載服務:

InstallUtil.exe  -u C:\windowServiceTest\windowService_Hello\bin\Debug\WindowService_HelloWorld.exe

 

 

10.檢驗是否有效果

在D盤發現log.txt文件,打開如下

 

 event log 所在如圖

 

 

可見,window服務上的定時任務已生效

 

參考網址

https://docs.microsoft.com/en-us/dotnet/framework/windows-services/walkthrough-creating-a-windows-service-application-in-the-component-designer

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM