Windows服務創建和運行
適用場景:
ASP.Net通常是一個無狀態的提供程序,不支持持續運行代碼或者定時執行某段代碼,所以我們需要構建自己的Windows服務來運行那些定時任務。
項目中需要定時處理數據時可以使用服務,比如短信發送,郵件提醒,和其他信息系統集合對接等定時任務
話不多說,簡單介紹如何創建
1.新建服務
從 Visual Studio“文件”菜單中,選擇“新建” > “項目”(或按 Ctrl+Shift+N),打開“新建項目”窗口
導航到並選擇“Windows 服務 (.NET Framework)”項目模板。


2.更改服務名稱:
右擊“屬性”,找到“ServiceName”屬性,修改成“MyService”
3.添加安裝程序
(1)右擊“Service.cs[設計]”窗口,選擇“添加安裝程序”。
可以看見項目中自動多了“serviceProcessInstall1”,"serviceInstaller1"這兩個文件。

(2) 設置組件serviceProcessInstaller1的主要屬性,Accout:賬戶類型,LocalSystem本地系統服務;

4.添加項目需要的業務代碼
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.ServiceProcess; 5 using System.Text; 6 using System.Threading.Tasks; 7 namespace WindowsService 8 { 9 static class Program 10 { 11 /// <summary> 12 /// 應用程序的主入口點。 13 /// </summary> 14 static void Main() 15 { 16 ServiceBase[] ServicesToRun; 17 ServicesToRun = new ServiceBase[] 18 { 19 new Service1() 20 }; 21 ServiceBase.Run(ServicesToRun); 22 } 23 } 24 }
打開“Program.cs”,可以看到服務啟動后,首先執行Service1。
這里,我們已5秒鍾一個輪詢,寫一條日志信息為例。
(1)首先添加文件夾“Utils”,添加類“Common.cs”,用於記錄日志
1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Text; 6 using System.Threading.Tasks; 7 namespace WindowsService.Utils 8 { 9 public static class Common 10 { 11 public static void WriteLogs(string content) 12 { 13 string path = AppDomain.CurrentDomain.BaseDirectory; 14 string LogName = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace.Split('.')[0]; 15 string[] sArray = path.Split(new string[] { LogName }, StringSplitOptions.RemoveEmptyEntries); 16 string aa = sArray[0] + "\\" + LogName + "Log\\"; 17 path = aa; 18 if (!string.IsNullOrEmpty(path)) 19 { 20 if (!Directory.Exists(path)) 21 { 22 Directory.CreateDirectory(path); 23 } 24 path = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";// 25 if (!File.Exists(path)) 26 { 27 FileStream fs = File.Create(path); 28 fs.Close(); 29 } 30 if (File.Exists(path)) 31 { 32 StreamWriter sw = new StreamWriter(path, true, System.Text.Encoding.Default); 33 sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "----" + content + "\r\n"); 34 sw.Close(); 35 } 36 } 37 } 38 } 39 }

(2)創建業務代碼類“HandleService.cs”
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using WindowsService.Utils; 7 namespace WindowsService 8 { 9 public class HandleService 10 { 11 public static void ActionRun(ref bool isRun) 12 { 13 try { 14 isRun = true; 15 //業務代碼 16 Common.WriteLogs("這是一條日志"); 17 18 } 19 catch (Exception ex) 20 { 21 Common.WriteLogs(ex.Message); 22 } 23 finally 24 { 25 isRun = false; 26 } 27 } 28 } 29 }
(3)設置Service1的定時觸發功能,
需要添加定時器Timer,定時執行上一步創建的“HandleService.cs”中的業務邏輯,完整代碼如下
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Diagnostics; 6 using System.Linq; 7 using System.ServiceProcess; 8 using System.Text; 9 using System.Threading.Tasks; 10 using WindowsService.Utils; 11 namespace WindowsService 12 { 13 public partial class Service1 : ServiceBase 14 { 15 public Service1() 16 { 17 InitializeComponent(); 18 } 19 System.Timers.Timer _timer = new System.Timers.Timer(); 20 private bool isRun = false; 21 protected override void OnStart(string[] args) 22 { 23 try 24 { 25 int _interval = 5 * 1000; 26 _timer.Interval = _interval; 27 _timer.AutoReset = true; 28 _timer.Enabled = true; 29 _timer.Elapsed += new System.Timers.ElapsedEventHandler(ActionRun); 30 Common.WriteLogs("服務已啟動"); 31 } 32 catch (Exception ex) 33 { 34 Common.WriteLogs(ex.Message); 35 } 36 } 37 private void ActionRun(object sender, System.Timers.ElapsedEventArgs e) 38 { 39 try 40 { 41 if (!isRun) 42 { 43 HandleService.ActionRun(ref isRun); 44 } 45 } 46 catch (Exception ex) 47 { 48 Common.WriteLogs("Error:" + ex.Message); 49 } 50 } 51 protected override void OnStop() 52 { 53 _timer.AutoReset = false; 54 _timer.Enabled = false; 55 _timer.Stop(); 56 Common.WriteLogs("服務已停止"); 57 } 58 } 59 } 60
生成項目文件,全部生成成功后,就要開始服務的安裝和啟動
5.服務的安裝和啟動
項目成功后,在bin文件夾下找到生成的exe文件和exe.config文件,前者是運行程序,后者是服務的配置信息,實際項目中可以通過更改config中的內容,修改服務的配置信息。

安裝和卸載主要使用的是.NET提供的InstallUtil.exe這個文件 ,文件位於C盤對應的目錄下 C:\Windows\
Microsoft.NET\Framework64\v4.0.30319,拷貝至和exe同一個目錄bin下。
新建bat文件,用於安裝,啟動,卸載,停止,重啟服務

1 安裝.bat: 2 sc create MyWinService binPath= "%~dp0WindowsService.exe" start= auto 3 net start MyWinService 4 pause 5
1 啟動.bat 2 net start MyWinService 3 pause 4
1 停止.bat 2 net stop MyWinService 3 pause
1 卸載.bat 2 net stop MyWinService 3 sc delete MyWinService binPath= "%~dp0JDWindowsService.exe" start= auto 4 pause
1 重啟.bat 2 net stop MyWinService 3 net start MyWinService 4 pause
6.運行安裝文件和啟動服務
雙擊“安裝.bat”,彈出cmd窗口,如下圖,表示安裝成功:

雙擊“啟動.bat”,如下圖表示成功啟動服務


7.查看業務代碼的日志寫入是否成功
找到項目文件同一個目錄下的Log文件,找到日志,如下圖所示:

可以看到日志文件每隔5秒會寫入一條日志文件,至此整個服務運行成功。
本文源碼下載:
提取碼:a62m