創(chuàng)建項(xiàng)目
創(chuàng)建項(xiàng)目,在Windows下選擇Windows服務(wù)(.NET Framework)。創(chuàng)建名稱為indowsService_Test,如下圖。
系統(tǒng)默認(rèn)創(chuàng)建Service1.cs。 打開Serice1.cs的屬性頁,將ServiceName修改為ServiceTest,如下圖:
添加定時(shí)器
在vs 主菜單中選“工具”項(xiàng),再選“選擇工具箱項(xiàng)”,再勾選命名空間為System.Timers的Timer,如下圖: 現(xiàn)在在工具箱中可以看到Timer組件如下圖所示。
將其拖入至Service1設(shè)計(jì)界面。將timer1的enabled 屬性設(shè)置為true,Interval屬性設(shè)置為1000。 雙擊timer1,自動(dòng)生成timer1_Elapsed事件。
添加業(yè)務(wù)代碼編輯Service1.cs,引入 System.Threading命名空間并修改代碼如下:
public partial classService1 :ServiceBase { privateThread thdStart; privateint numTimes; public Service1() { InitializeComponent(); }
protected override void OnStart(string[] args) { thdStart = newThread(newThreadStart(timer1.Start)); thdStart.Start(); }
protectedoverridevoid OnStop() { }
privatevoid timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { this.timer1.Stop(); numTimes++; string filePath =@"c:\ServiceTest.log"; string strCont =DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") +"第" + numTimes +"次執(zhí)行。"; System.IO.File.AppendAllText(filePath, strCont); this.timer1.Start(); } }
為WindowsService_Test添加安裝程序在Service1設(shè)計(jì)界面下,右鍵彈出菜單,選擇“添加安裝程序” 在serviceProcessInstaller1屬性頁中將Account由User改為LocalSystem,
生成服務(wù)生成項(xiàng)目。 新建一個(gè)目錄,將項(xiàng)目的\bin\Debug目錄下生成的所有文件拷貝到該新的目錄,再在該目錄下建兩個(gè)批出處理文件,文件名可分別為install.bat和uninstall.bat,內(nèi)容分別如下: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe /i WindowsService_Test.exe C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe /u WindowsService_Testr.exe 注意:如果由于某種原因而使生成的平臺(tái)目標(biāo)設(shè)為x86,則命令中的framework64要改成framework. 部署和卸載服務(wù) 以部署到windows server 2008服務(wù)器為例,先須安裝NDP462-KB3151800-x86-x64-AllOS-ENU.exe即.netframework 4.6.2,如果在內(nèi)網(wǎng)環(huán)境下安裝.net4.6.2,則需要安裝 7.選擇下載好的cer文件,然后無限下一步。 NDP462-KB3151800-x86-x64-AllOS-ENU.exe安裝完畢后,將上述的文件夾拷貝到服務(wù)器的磁盤上,運(yùn)行其中的install.bat,然后再打開管理工具-服務(wù),找到WindowsService_Test項(xiàng),雙擊后點(diǎn)“啟動(dòng)”即可啟動(dòng)服務(wù),往后服務(wù)啟動(dòng)時(shí)會(huì)自動(dòng)啟動(dòng)該服務(wù)。 要卸載服務(wù),只需要運(yùn)行上述已經(jīng)拷貝到服務(wù)器的磁盤中的文件夾內(nèi)的uninstall.bat文件即可。 |
|