一、需求
我們有時候可能會想要做一些定時任務,例如每隔一段時間去訪問某個網站,或者下載一些東西到我們服務器上等等之類的事情,這時候windows service 是一個不錯的選擇。
二、實現
1、打開Visua studio2013新建一個windows Service程序,我命名為TimerService
注意,這里的.NET Framwork框架的選擇要與你電腦上的框架一致,我這里選擇的是4.0
2、在Service1設計器中右擊空白處選擇查看代碼
3.在Service1.cs中設定定時的時間間隔以及定時執行的任務這里的Onstart方法定義定時器的開始執行,執行的時間間隔,以及時間間隔達到后所要執行的方法,我這里是執行了一個文件寫入的方法,代碼如下
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceProcess; using System.Text; using System.Timers; namespace TimerService { public partial class Service1 : ServiceBase { Timer timer; public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { timer = new Timer(1000); timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed); timer.Start(); WriteLog("服務啟動"); } protected override void OnStop() { timer.Stop(); timer.Dispose(); WriteLog("服務停止"); } protected void Timer_Elapsed(object sender, ElapsedEventArgs e) { WriteLog("服務執行中"); } protected void WriteLog(string str) { string filePath = AppDomain.CurrentDomain.BaseDirectory + "Log.txt"; StreamWriter sw = null; if (!File.Exists(filePath)) { sw = File.CreateText(filePath); } else { sw = File.AppendText(filePath); } sw.Write(str + DateTime.Now.ToString() + Environment.NewLine); sw.Close(); } } }
4、在Service1設計器中右擊空白處,選擇添加安裝程序,會添加一個ProjectInstaller設計器
5、在ProjectInstaller設計器中選擇serviceProcessInstaller,右擊查看屬性,將Account的值改為LocalSystem
6、在ProjectInstaller設計器中選擇serviceInstaller1,右擊查看屬性,這里的ServiceName就是要在服務器的服務中顯示的名稱,我將其命名我TimerService
7、右擊解決方案,點擊生成解決方案
三、安裝
1、打開剛剛新建建項目所在的文件夾,找到bin文件下面的debug文件夾,即D:\用戶目錄\我的文檔\Visual Studio 2013\Projects\TimerService\TimerService\bin\Debug,里面有個TimerService.exe應用程序,就是我們所要執行的項目
2、打開文件夾C:\Windows\Microsoft.NET\Framework\v4.0.30319,可以看到里面有一個InstallUtil.exe的應用程序,這就是我們要的安裝工具,這里的Framework的版本與我們項目的Framework版本保持一致
3、打開cmd輸入cd C:\Windows\Microsoft.NET\Framework\v4.0.30319指令,然后再輸入InstallUtil D:\用戶目錄\我的文檔\Visual~1\Projects\TimerService\TimerService\bin\Debug\TimerService.exe,即可完成安裝
4、啟動任務管理器,點擊服務,找到名稱TemrService的服務,右擊啟動,即可將創建的定時服務啟動,這里的服務名稱就是我們在項目的serviceInstaller1的屬性里面設置的serviceName
5、在我們的D:\用戶目錄\我的文檔\Visual Studio 2013\Projects\TimerService\TimerService\bin\Debug文件下面會發現多了一個log.txt的文件,就是我們在項目中創建的文件,打開即可看到項目正常執行
四、卸載
要卸載應用服務也很簡單,只需要在cmd中輸入以下指令即可
InstallUtil /u D:\用戶目錄\我的文檔\Visual~1\Projects\TimerService\TimerService\bin\Debug\TimerService.exe