close

1.建立Windows Service 專案

a.PNG  

 

2.檢視程式碼

b.PNG  

 

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!");
      }
  }
 }
}
view raw gistfile1.txt hosted with ❤ by GitHub

4.完成後返回設計介面,並按下右鍵選擇「加入安裝程式」

加入安裝程式1.png

VS會自動建立ProjectInstaller.cs檔案,內有兩個物件,分別為「serviceProcessInstaller1」「serviceInstaller1」

 

 

 

加入安裝程式2.png  

*以上兩步驟與圖片取自 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]

  4.PNG  

Account : 代表啟動service的帳號,一般是LocalSystem,也有些需要設定其他帳號密碼(視情況而定)

 

[serviceInstaller1]

2.PNG

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.png  

選擇安裝專案

安裝服務2.PNG  

選擇檢視=>自訂動作

安裝服務3.png

 

出現畫面後選擇[加入自訂動作]

安裝服務4.png

 

選擇應用程式資料夾

安裝服務5.png

 

選擇[加入輸出]

 

 

 

 

 

安裝服務6.png

 

確認好專案名稱後,案下確定

安裝服務7.png

 

四個都要有

安裝服務8.png   

  接下來1.建置專案,建置後再 2.安裝專案

建置與安裝service.png  

 

6.安裝後,就可以至[服務]啟動service並驗證有沒有正確執行

完成1.PNG

 

完成2.PNG  

 

參考資料

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

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Kenny Lin 的頭像
    Kenny Lin

    Kenny的程式筆記

    Kenny Lin 發表在 痞客邦 留言(0) 人氣()