一、編寫windows服務
1、VS2017 - 創建服務Myservice
2、創建好項目之后 --- >> 雙擊 Service1.cs ---- >> 出現一個設計界面 ---->> 右鍵界面 --- >> 彈出對話框選擇 ”添加安裝程序“
3、在設計界面修改 serviceProcessInstaller1的屬性 Account 為 LocalSystem (也可用代碼修改)
4、在設計界面修改 serviceInstaller1 的屬性: display 為 myfirstservice ; description 為 我的首個服務 ; StartType 為 Automatic
5、修改Service1.cs 代碼如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; namespace myservice { public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { // TODO: 在此處添加代碼以啟動服務。 System.IO.File.AppendAllText(@"D:\Log.txt", " Service Start :" + DateTime.Now.ToString()); } protected override void OnStop() { // TODO: 在此處添加代碼以執行停止服務所需的關閉操作。 System.IO.File.AppendAllText(@"D:\Log.txt", " Service Stop :" + DateTime.Now.ToString()); } } }
6、生成解決方案,可以在項目的dubug目錄中找到 myservice.exe
二、SC命令=====安裝、開啟、配置、關閉windows服務
1、將myservice.exe放在英文目錄下,我的是 d:\myservice.exe
2、在cmd中,轉到D:並執行以下使命令進行服務安裝和啟動(這里的myserv 是自定義的名字)
sc create myserv binPath= "d:/myservice.exe"
sc config myserv start= auto //(自動) (DEMAND----手動、DISABLED----禁用) 並且start連着= ,而=的后面有一個空格 net start myserv
可以看到d盤下已生成了log.txt
3.刪除服務,執行以下代碼
sc delete myserv
4、為方便使用,可編輯為bat批處理文件
@echo.服務啟動...... @echo off @sc create myserv1 binPath= "d:\demo.exe" @net start myserv1 @sc config myserv1 start= AUTO @echo off @echo.啟動完畢! @pause
5.或在程序中用以下代碼安裝(參考http://www.cnblogs.com/pingming/p/5115320.html)
//安裝服務 string path = @"D:\demo.exe"; Process.Start("sc", "create myDemo binPath= \"" + path + "\" "); Console.WriteLine("安裝成功"); //卸載服務 Process.Start("sc", "delete KJLMDemo"); Console.WriteLine("卸載成功"); break;
6、定時執行任務:參考 https://www.cnblogs.com/Beau/p/3491063.html
//開始事件 protected override void OnStart(string[] args) { //定時事件 MyTimer(); } //結束事件 protected override void OnStop() { writeLog("服務結束時間:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } //實例化System.Timers.Timer private void MyTimer() { System.Timers.Timer MT = new System.Timers.Timer(30000); MT.Elapsed += new System.Timers.ElapsedEventHandler(MTimedEvent); MT.Enabled = true; } //構造System.Timers.Timer實例 間隔時間事件 private void MTimedEvent(object source, System.Timers.ElapsedEventArgs e) { //實現方法 }
關於定時器,System.Windows.Forms.Timer與System.Timers.Timer的區別,參考這里:http://www.cnblogs.com/lonelyxmas/archive/2009/10/27/1590604.html
