C#-Windows服務創建和運行
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.添加項目需要的業務代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace WindowsService
{
static class Program
{
/// <summary>
/// 應用程序的主入口點。
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1() //注意與你建的服務名稱一致
};
ServiceBase.Run(ServicesToRun);
}
}
}
打開“Program.cs”,可以看到服務啓動後,首先執行Service1。
這裏,我們已5秒鐘一個輪詢,寫一條日誌信息爲例。
(1)首先添加文件夾“Utils”,添加類“Common.cs”,用於記錄日誌
複製代碼
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsService.Utils
{
public static class Common
{
public static void WriteLogs(string content)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
string LogName = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace.Split('.')[0];
string[] sArray = path.Split(new string[] { LogName }, StringSplitOptions.RemoveEmptyEntries);
string aa = sArray[0] + "\\" + LogName + "Log\\";
path = aa;
if (!string.IsNullOrEmpty(path))
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";//
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Close();
}
if (File.Exists(path))
{
StreamWriter sw = new StreamWriter(path, true, System.Text.Encoding.Default);
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "----" + content + "\r\n");
sw.Close();
}
}
}
}
}
(2)創建業務代碼類“HandleService.cs”
複製代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WindowsService.Utils;
namespace WindowsService
{
public class HandleService
{
public static void ActionRun(ref bool isRun)
{
try {
isRun = true;
//業務代碼:這裏可以寫你的業務相關的代碼
Common.WriteLogs("這是一條日誌");
}
catch (Exception ex)
{
Common.WriteLogs(ex.Message);
}
finally
{
isRun = false;
}
}
}
}
複製代碼
(3)設置Service1的定時觸發功能,
需要添加定時器Timer,定時執行上一步創建的“HandleService.cs”中的業務邏輯,完整代碼如下
複製代碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using WindowsService.Utils;
namespace WindowsService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
System.Timers.Timer _timer = new System.Timers.Timer();
private bool isRun = false;
protected override void OnStart(string[] args)
{
try
{
//設置計時器事件間隔執行時間,以毫秒爲單位,這裏設置5秒執行一次
int _interval = 5 * 1000;
_timer.Interval = _interval;
_timer.AutoReset = true; //是否自動啓動
_timer.Enabled = true; //是否開啓計時器
//到達時間時,執行的事件
_timer.Elapsed += new System.Timers.ElapsedEventHandler(ActionRun);
Common.WriteLogs("服務已啓動");
}
catch (Exception ex)
{
Common.WriteLogs(ex.Message);
}
}
private void ActionRun(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
//是否開啓計時器
if (!isRun)
{
HandleService.ActionRun(ref isRun);
}
}
catch (Exception ex)
{
Common.WriteLogs("Error:" + ex.Message);
}
}
protected override void OnStop()
{
_timer.AutoReset = false;
_timer.Enabled = false;
_timer.Stop();
Common.WriteLogs("服務已停止");
}
}
}
複製代碼
生成項目文件,全部生成成功後,就要開始服務的安裝和啓動
5.服務的安裝和啓動
項目成功後,在bin文件夾下找到生成的exe文件和exe.config文件,前者是運行程序,後者是服務的配置信息,實際項目中可以通過更改config中的內容,修改服務的配置信息。
安裝和卸載主要使用的是.NET提供的InstallUtil.exe這個文件 ,文件位於C盤對應的目錄下 C:\Windows\Microsoft.NET\Framework64\v4.0.30319,拷貝至和exe同一個目錄bin下。
新建bat文件,用於安裝,啓動,卸載,停止,重啓服務
安裝.bat:
MyWinService:給你的服務起一個別名
WindowsService.exe:是你的服務項目生成的文件,
“%~dp0”:這部分是固定不變的,例如 “%~dp0你的服務項目名稱.exe”,本文的服務項目名稱是 WindowsService
sc create MyWinService binPath= "%~dp0WindowsService.exe" start= auto
net start MyWinService
pause
啓動.bat
net start MyWinService
pause
停止.bat
net stop MyWinService
pause
重啓.bat
net stop MyWinService
net start MyWinService
pause
卸載.bat
MyWinService:給你的服務起一個別名
WindowsService.exe:是你的服務項目生成的文件,
“%~dp0JD”:這部分是固定不變的,例如 “%~dp0JD你的服務項目名稱.exe”,本文的服務項目名稱是 WindowsService
net stop MyWinService
sc delete MyWinService binPath= "%~dp0JDWindowsService.exe" start= auto
pause
6.運行安裝文件和啓動服務
雙擊“安裝.bat”,彈出cmd窗口,如下圖,表示安裝成功:
雙擊“啓動.bat”,如下圖表示成功啓動服務
7.查看業務代碼的日誌寫入是否成功
找到項目文件同一個目錄下的Log文件,找到日誌,如下圖所示:
可以看到日誌文件每隔5秒會寫入一條日誌文件,至此整個服務運行成功。
本文源碼下載:
鏈接:https://pan.baidu.com/s/1gsJ7m12NP7puxXNb4IPVEA
提取碼:a62m