標籤:9.png onstop org sock interval zcl dir domain ini
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 = 5000;//每5秒執行一次 timer.Enabled = true; } //定時執行事件 private void TimedEvent(object sender, System.Timers.ElapsedEventArgs e) { //商務邏輯代碼 } protected override void OnStart(string[] args) { this.WriteLog("OnStart"); } protected override void OnStop() { this.WriteLog("OnStop"); } protected override void OnShutdown() { this.WriteLog("OnShutdown"); } #region 記錄日誌 /// <summary> /// 記錄日誌 /// </summary> /// <param name="msg"></param> private void WriteLog(string msg) { //string path = @"C:\log.txt"; //該記錄檔會存在windows服務程式目錄下 string path = AppDomain.CurrentDomain.BaseDirectory + "\\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 }}
5、編譯產生,安裝windows服務至Windows系統。
完成開發後,對整各項目進行編譯產生。在windows服務開發檔案夾“\bin\Debug”下,就是我們需要安裝的服務,建議把裡面的所有檔案拷貝至系統裡的某個目錄進行安裝。
我是把整個個檔案夾裡的檔案拷貝到c:\WindowService檔案夾下。然後開啟目錄C:\Windows\Microsoft.NET\Framework64\v4.0.30319,拷貝裡面的InstallUtil.exe檔案至c:\WindowService檔案夾下)。
注意:我的系統是windows10,64位系統,我的服務也將安裝至64位系統下,所以我是進入C:\Windows\Microsoft.NET\Framework64\v4.0.30319目錄拷貝InstallUtil.exe檔案。各位安裝的時候,根據你安裝的目標系統,來覺得是拷貝哪個framework哪個版本,具體是64位的還是32位的也由你系統決定。
做好以上工作後就可以安裝了,開啟cdm就可執行安裝了(一定要以管理員身份運行喲,要不然安裝時會報“Windows服務安裝異常:System.Security.SecurityException: 未找到源,但未能搜尋某些或全部事件”)。
以下是安裝命令、啟動服務命令、停止服務命令、卸載服務命令:
安裝命令:D:\WindowsService\Timer\InstallUtil.exe D:\WindowsService\Timer\WindowsServiceTest.exe
啟動服務命令:net start 搜才Organiz用戶端資料同步服務
關閉服務命令:net stop 搜才Organiz用戶端資料同步服務
卸載服務命令:D:\WindowsService\Timer\InstallUtil.exe -u D:\WindowsService\Timer\WindowsServiceTest.exe
vs2015開發Windows服務