標籤:style class blog java http tar
功能說明: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)