C# 创建Windows服务。服务功能:定时操作数据库
一、創(chuàng)建window服務(wù)
1、新建項(xiàng)目-->選擇Windows服務(wù)。默認(rèn)生成文件包括Program.cs,Service1.cs
2、在Service1.cs添加如下代碼:
???????System.Timers.Timer?timer1;??//計(jì)時(shí)器
????????public?Service1()
????????{
????????????InitializeComponent();
????????}
????????protected?override?void?OnStart(string[]?args)??//服務(wù)啟動(dòng)執(zhí)行
????????{
????????????timer1?=?new?System.Timers.Timer();
????????????timer1.Interval?=?3000;??//設(shè)置計(jì)時(shí)器事件間隔執(zhí)行時(shí)間
????????????timer1.Elapsed?+=?new?System.Timers.ElapsedEventHandler(timer1_Elapsed);
????????????timer1.Enabled?=?true;
????????}
????????protected?override?void?OnStop()??//服務(wù)停止執(zhí)行
????????{
????????????this.timer1.Enabled?=?false;
????????}
?
????????private?void?timer1_Elapsed(object?sender,?System.Timers.ElapsedEventArgs?e)
????????{
????????????//執(zhí)行SQL語(yǔ)句或其他操作
????????}
?
二、添加window服務(wù)安裝程序
1、打開Service1.cs【設(shè)計(jì)】頁(yè)面,點(diǎn)擊右鍵,選擇【添加安裝程序】,會(huì)出現(xiàn)serviceInstaller1和serviceProcessInstaller1兩個(gè)組件
2、將serviceProcessInstaller1的Account屬性設(shè)為【LocalSystem】, serviceInstaller1的StartType屬性設(shè)為【Automatic】,ServiceName屬性可設(shè)置服務(wù)名稱,此后在【管理工具】--》【服務(wù)】中即顯示此名稱
3、ProjectInstaller.cs文件,在安裝服務(wù)后一般還需手動(dòng)啟動(dòng)(即使上述StartType屬性設(shè)為【Automatic】),可在ProjectInstaller.cs添加如下代碼實(shí)現(xiàn)安裝后自動(dòng)啟動(dòng)
????public?ProjectInstaller()
????????{
????????????InitializeComponent();
????????????this.Committed?+=?new?InstallEventHandler(ProjectInstaller_Committed);???
????????}
????????private?void?ProjectInstaller_Committed(object?sender,?InstallEventArgs?e)
????????{
????????????//參數(shù)為服務(wù)的名字
????????????System.ServiceProcess.ServiceController?controller?=?new?System.ServiceProcess.ServiceController("服務(wù)名稱");
????????????controller.Start();
????????}???
?
三、安裝、卸載window服務(wù)
1、輸入cmd(命令行),輸入cd?C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319,2.0為cd?C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
2、安裝服務(wù)(項(xiàng)目生成的exe文件路徑)
??InstallUtil?"E:\WindowsService1\bin\Debug\WindowsService1.exe"
3、卸載服務(wù)
??InstallUtil??/u?"E:\WindowsService1\bin\Debug\WindowsService1.exe"
四、查看window服務(wù)
??? services.msc
控制面板-->管理工具-->服務(wù),可在此手動(dòng)啟動(dòng),停止服務(wù)
五、調(diào)試window服務(wù)
1、通過【事件查看器】查看
2、直接在程序中調(diào)試(菜單-->調(diào)試-->附加進(jìn)程-->服務(wù)名(這里的服務(wù)名是項(xiàng)目名稱,不是ServiceName屬性自定義的名稱,所以建議自定義名稱和項(xiàng)目名稱保持一致,另外需勾選【顯示所有用戶的進(jìn)程】才能看到服務(wù)名)-->附加
?? 這里附加的進(jìn)程名應(yīng)該是:WindowsService1.exe 而不是 WindowsService1.vshost.exe。WindowsService1.exe 默認(rèn)不會(huì)出現(xiàn),必須勾選【顯示所有用戶的進(jìn)程】【顯示所有會(huì)話中的進(jìn)程】
3.?在程序中打斷點(diǎn)調(diào)試即可,另外調(diào)試服務(wù)時(shí)服務(wù)必須已啟動(dòng)(管理工具-->服務(wù))
?
?
?
例子 ?http://files.cnblogs.com/lyl6796910/NC.JPushNotification.rar
總結(jié)
以上是生活随笔為你收集整理的C# 创建Windows服务。服务功能:定时操作数据库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开始——“运行”命令集
- 下一篇: C# WinForm开发系列 - Dat