今天剛剛爲本身的項目添加了windows服務,以服務的形式運行後臺系統,爲前端提供接口服務,下面說一下具體怎麼爲vs項目添加windows服務html
在上圖空白處點擊右鍵,以下圖所示前端
VS2015會自動新建一個帶有默認配置的安裝程序類,以下圖:windows
iide
以下圖所示:學習
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.IO; namespace OrganizClientSocketService { public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); System.Timers.Timer timer = new System.Timers.Timer(); timer.Elapsed += new System.Timers.ElapsedEventHandler(TimedEvent); timer.Interval = 10000;//每5秒執行一次 timer.Enabled = true; } //定時執行事件 private void TimedEvent(object sender, System.Timers.ElapsedEventArgs e) { //業務邏輯代碼 } protected override void OnStart(string[] args) { this.WriteLog("【服務啓動】"); } protected override void OnStop() { this.WriteLog("服務中止】"); } protected override void OnShutdown() { this.WriteLog("【計算機關閉】"); } #region 記錄日誌 /// <summary> /// 記錄日誌 /// </summary> /// <param name="msg"></param> private void WriteLog(string msg) { //該日誌文件會存在windows服務程序目錄下 string path = AppDomain.CurrentDomain.BaseDirectory + "\\log.txt"; //string path = @"C:\log.txt"; FileInfo file = new FileInfo(path); if (!file.Exists) { FileStream fs; fs = File.Create(path); fs.Close(); } using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine(DateTime.Now.ToString() + " " + msg); } } } #endregion } }
完成開發後,對整各項目進行編譯生成。在windows服務開發文件夾「\bin\Debug」下,就是咱們須要安裝的服務,建議把裏面的全部文件拷貝至系統裏的某個目錄進行安裝。this
我是把整個個文件夾裏的文件拷貝到c:\WindowService文件夾下。而後打開目錄C:\Windows\Microsoft.NET\Framework64\v4.0.30319,拷貝里面的InstallUtil.exe文件至c:\WindowService文件夾下)。spa
注意:個人系統是windows10,64位系統,個人服務也將安裝至64位系統下,因此我是進入C:\Windows\Microsoft.NET\Framework64\v4.0.30319目錄拷貝InstallUtil.exe文件。各位安裝的時候,根據你安裝的目標系統,來以爲是拷貝哪一個framework哪一個版本,具體是64位的仍是32位的也由你係統決定。日誌
作好以上工做後就能夠安裝了,打開cdm就可執行安裝了(必定要以管理員身份運行喲,要否則安裝時會報「Windows服務安裝異常:System.Security.SecurityException: 未找到源,但未能搜索某些或所有事件」)。code
如下是安裝命令、啓動服務命令、中止服務命令、卸載服務命令:htm
安裝命令:C:\WindowService\InstallUtil.exe C:\WindowService\OrganizClientSocketService.exe
啓動服務命令:net start 搜才Organiz客戶端數據同步服務
關閉服務命令:net stop 搜才Organiz客戶端數據同步服務
卸載服務命令:C:\WindowService\InstallUtil.exe -u C:\WindowService\OrganizClientSocketService.exe
版權全部,文章來源:http://www.cnblogs.com/sagecheng/p/7397310.html
我的能力有限,本文內容僅供學習、探討,歡迎指正、交流。
http://www.cnblogs.com/sagecheng/articles/7397293.html