1.建立Windows Service 專案
2.檢視程式碼
3.編輯程式碼(sample)
using System.IO; | |
using System.Timers; | |
namespace WindowsService1 | |
{ | |
public partial class Service1 : ServiceBase | |
{ | |
private String path = "D:\\log.txt"; //寫檔路徑 | |
public Service1() | |
{ | |
InitializeComponent(); | |
} | |
protected override void OnStart(string[] args) //Service啟動時要做什麼 | |
{ | |
System.Timers.Timer MyTimer = new System.Timers.Timer(); //建立一個timer | |
MyTimer.Elapsed += new ElapsedEventHandler(writeLog); //Elapsed代表,timer設定的時間到後要做什麼事情 | |
//做什麼事情可以寫成method丟進去,sample為寫log | |
MyTimer.Interval = 2000; //代表時間間隔,單位為毫秒,設定2000代表2秒 | |
MyTimer.Start(); //啟動timer | |
} | |
private void writeLog(object sender, ElapsedEventArgs e) //寫log | |
{ | |
using (StreamWriter sw = File.AppendText(path)) | |
{ | |
sw.WriteLine(System.DateTime.Now.ToString()); | |
} | |
} | |
protected override void OnStop() //Service停止時要做什麼 | |
{ | |
using (StreamWriter sw = File.AppendText(path)) | |
{ | |
sw.WriteLine("Service stop!"); | |
} | |
} | |
} | |
} |
4.完成後返回設計介面,並按下右鍵選擇「加入安裝程式」
VS會自動建立ProjectInstaller.cs檔案,內有兩個物件,分別為「serviceProcessInstaller1」「serviceInstaller1」
*以上兩步驟與圖片取自 http://gogo1119.pixnet.net/blog/post/27575780-%5Bc%23%5D-windows-service%E5%BB%BA%E7%AB%8B%E7%AF%84%E4%BE%8B
接下來設定這兩個元件的屬性
[serviceProcessInstaller1]
Account : 代表啟動service的帳號,一般是LocalSystem,也有些需要設定其他帳號密碼(視情況而定)
[serviceInstaller1]
Description : 代表service安裝後顯示的"敘述"
Display Name : 代表service安裝後顯示的名稱
Start Type : 代表service啟動的性質,Manual代表重開機後要手動啟動
5.建立安裝專案,另外也可以使用DOS指令安裝service,
以下步驟圖片與說明部份取自 http://gogo1119.pixnet.net/blog/post/27575780-%5Bc%23%5D-windows-service%E5%BB%BA%E7%AB%8B%E7%AF%84%E4%BE%8B
加入安裝專案
選擇安裝專案
選擇檢視=>自訂動作
出現畫面後選擇[加入自訂動作]
選擇應用程式資料夾
選擇[加入輸出]
確認好專案名稱後,案下確定
四個都要有
接下來1.建置專案,建置後再 2.安裝專案
6.安裝後,就可以至[服務]啟動service並驗證有沒有正確執行
參考資料
http://gogo1119.pixnet.net/blog/post/27575780-%5Bc%23%5D-windows-service%E5%BB%BA%E7%AB%8B%E7%AF%84%E4%BE%8B
https://msdn.microsoft.com/zh-tw/library/system.timers.timer.elapsed%28v=vs.110%29.aspx
https://msdn.microsoft.com/zh-tw/library/system.timers.timer.interval(v=vs.110).aspx