1.在VS2010建立windows service工程windows
文件---新建---項目----windows服務。ide
2.雙擊service1.cs,在onstart中寫具體代碼,注意若是代碼執行須要很長時間,則須要將方法放在子線程中,不然windows服務會啓動不起來。工具
protected override void OnStart(string[] args) { try { log4.Info("服務已啓動:"); ExecuteTimerTask(); } catch (Exception ex) { log4.Error("服務啓動失敗", ex); } }
3.定時器Quartz的使用ui
public void ExecuteTimerTask() { //初始化委託變量 TimerTaskDelegate task = new TimerTaskDelegate(SpaceTask); //建立定時任務線程並啓動 Thread ThreadTimerTask = TimerTask.CreateTimerTaskThread(task); ThreadTimerTask.IsBackground = true; ThreadTimerTask.Start(); log4.Info("定時任務已啓動:"); }
4.添加安裝程序spa
在PageRequestService.cs[設計]右鍵---添加安裝程序,會出現線程
注意:account選擇localhost ;StartType選擇Automatic(開機自動執行)設計
5.安裝服務調試
管理員身份運行cmd,執行如下命令日誌
開始-運行-cmdcode
安裝命令
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe C:\PageRequestService\PageRequestService.exe
卸載命令
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe C:\PageRequestService\PageRequestService.exe -u
在控制面板---管理工具-----服務----右鍵----啓動服務
6.異常狀況
若是不能正常啓動服務,說明服務有錯誤。能夠利用「日誌查看器」查看錯誤信息。(調試比較麻煩)。
注意每次對服務改動的話,都必須從新安裝。
安裝時報錯以下:
An exception occurred during the Install phase.
System.InvalidOperationException: Cannot open Service Control Manager on computer '.'. This operation might require other privileges.
The inner exception System.ComponentModel.Win32Exception was thrown with the following error message: 拒絕訪問。.
The Rollback phase of the installation is beginning.
See the contents of the log file for the C:\PageRequestService\bin\Debug\PageRequestService.exe assembly's progress.
The file is located at C:\PageRequestService\bin\Debug\PageRequestService.InstallLog.
The Rollback phase completed successfully.
The transacted install has completed.
因爲自動寫系統日誌時出錯(例如沒有權限),所以將WindowsService的AutoLog屬性設爲false,便可完成安裝。
源碼下載:WinService Source