功能說明:C#創建一個windows服務,服務啟動時D:\mcWindowsService.txt寫入數據,服務運行期間每隔兩秒寫入當前時間。
原理這些就不說了,三語兩語說不清楚,直接貼一個實例。不能貼圖片!!那個壓縮文裡面是word文檔!!有圖有真相
1.建立空白項目
2.添加創建windows服務需要的引用,選擇System.ServiceProcess。
3.創建服務類,繼承ServiceBase,類的源代碼在後面。
4. 添加windows服務的安裝類。
(1)在類名或者解決方案中新建視圖:
(2)上一步後會出來類的視圖,右鍵選擇查看設計器:
(3)在設計視圖裡面添加安裝器(有可能會彈出警告框,如圖,不用管):
服務創建完成!
安裝運行就不用說了吧!!
6 服務類源代碼():
C#代碼
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Timers;
-
- namespace SR171
- {
- class Service17: System.ServiceProcess.ServiceBase
- {
-
- public Service17()//可以自己設定
- {
- this.ServiceName = "MyServiceForShowTime";
- this.CanStop = true;
- this.CanPauseAndContinue = true;
- this.AutoLog = true;
-
- #region 定時器事件
- Timer aTimer = new Timer(); //System.Timers,不是form的
- aTimer.Elapsed += new ElapsedEventHandler(TimedEvent);
- aTimer.Interval = 2 * 1000; //配置文件中配置的秒數
- aTimer.Enabled = true;
- #endregion
- }
- public static void Main()//必須寫
- {
- System.ServiceProcess.ServiceBase.Run(new Service17());
- }
- protected override void OnStart(string[] args)//自己根據要求覆寫
- {
- FileStream fs = new FileStream(@"d:\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);
-
- StreamWriter m_streamWriter = new StreamWriter(fs);
-
- m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
-
- m_streamWriter.WriteLine("mcWindowsService: Service Started" + DateTime.Now.ToString() + "\n");
-
- m_streamWriter.Flush();
-
- m_streamWriter.Close();
-
- fs.Close();
-
-
- }
- protected override void OnStop()
- {
-
- FileStream fs = new FileStream(@"d:\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);
-
- StreamWriter m_streamWriter = new StreamWriter(fs);
-
- m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
-
- m_streamWriter.WriteLine(" mcWindowsService: Service Stopped " + DateTime.Now.ToString() + "\n");
-
- m_streamWriter.Flush();
-
- m_streamWriter.Close();
-
- fs.Close();
-
- }
-
-
- private static void TimedEvent(object source, ElapsedEventArgs e) //運行期間執行
- {
- FileStream fs = new FileStream(@"d:\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);
-
- StreamWriter m_streamWriter = new StreamWriter(fs);
-
- m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
-
- m_streamWriter.WriteLine(" Running.11.. " + DateTime.Now.ToString() + "\n");
-
- m_streamWriter.Flush();
-
- m_streamWriter.Close();
-
- fs.Close();
- }
-
- }
- }
- C_創建windows服務搭配定時器Timer使用實例(用代碼做,截圖版).rar (462.8 KB)