1. 程式人生 > >C#建立windows服務並定時執行

C#建立windows服務並定時執行

一、建立window服務

1、新建專案-->選擇Windows服務。預設生成檔案包括Program.cs,Service1.cs

2、在Service1.cs新增如下程式碼:

       System.Timers.Timer timer1;  //計時器

        public Service1()

        {

            InitializeComponent();

        }

        protected override void OnStart(string[] args)  //服務啟動執行

        {

            timer1 = new System.Timers.Timer();

            timer1.Interval = 3000;  //設定計時器事件間隔執行時間

            timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);

            timer1.Enabled = true;

        }

        protected override void OnStop()  //服務停止執行

        {

            this.timer1.Enabled = false;

        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)

        {

            //執行SQL語句或其他操作

        }

二、新增window服務安裝程式

1、開啟Service1.cs【設計】頁面,點選右鍵,選擇【新增安裝程式】,會出現serviceInstaller1和serviceProcessInstaller1兩個元件

2、將serviceProcessInstaller1的Account屬性設為【LocalSystem】, serviceInstaller1的StartType屬性設為【Automatic】,ServiceName屬性可設定服務名稱,此後在【管理工具】--》【服務】中即顯示此名稱

3、ProjectInstaller.cs檔案,在安裝服務後一般還需手動啟動(即使上述StartType屬性設為【Automatic】),可在ProjectInstaller.cs新增如下程式碼實現安裝後自動啟動

    public ProjectInstaller()

        {

            InitializeComponent();

            this.Committed += new InstallEventHandler(ProjectInstaller_Committed);   

        }

        private void ProjectInstaller_Committed(object sender, InstallEventArgs e)

        {

            //引數為服務的名字

            System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController("服務名稱");

            controller.Start();

        }   

三、安裝、解除安裝window服務

1、輸入cmd(命令列),輸入cd C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319,2.0為cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

2、安裝服務(專案生成的exe檔案路徑)

  InstallUtil "E:\WindowsService1\bin\Debug\WindowsService1.exe"

3、解除安裝服務

  InstallUtil  /u "E:\WindowsService1\bin\Debug\WindowsService1.exe"

四、檢視window服務

控制面板-->管理工具-->服務,可在此手動啟動,停止服務

五、除錯window服務

1、通過【事件檢視器】檢視

2、直接在程式中除錯(選單-->除錯-->附加程序-->服務名(這裡的服務名是專案名稱,不是ServiceName屬性自定義的名稱,所以建議自定義名稱和專案名稱保持一致,另外需勾選【顯示所有使用者的程序】才能看到服務名)-->附加

3. 在程式中打斷點除錯即可,另外除錯服務時服務必須已啟動(管理工具-->服務)