一起動手實現Windows服務程序(監控網站是否能訪問)

請移步我的博客查閱並下載所有資源以及源代碼 http://www.cckan.net

 

什麼是Windows服務程序員?

C# Windows服務程序開發之前要明白什麼是Windows服務,Windows Service,也稱Windows服務,是32位Windows操作系統中一種長期運行的後臺程序。它們長期後臺運行,沒有用戶界面,默默無聞,但它們卻是支持Windows正常運行的幕後英雄,卻永無出頭之日。我稱之爲最穩定的程序之一。

  因爲他會隨着系統的自動啓動而啓動,自動關閉而關閉,不需要用戶直接登錄,直接開機就可以啓動。

很方便 穩定。這類程序一般是做爲服務或者是監控類的東東。也正是因爲他的穩定和方便。

但在C#裏面怎麼實現它呢?

我們一起來看看吧,

我以VS2010爲例子。我們先來新建一個Window服務項目 如下圖所示

我們再來看看VS2010都給我們創建了什麼

我們一起來看看Services1裏面都有什麼吧

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 WindowsService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 開啓服務時要執行的方法
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {

        }

        /// <summary>
        /// 停止服務時要執行的方法
        /// </summary>
        protected override void OnStop()
        {

        }
    }
}

其實裏面只有兩個方法,OnStart啓動服務時要執行的方法,也就是程序的入口了。

下面咱們一起來做一個監控自己網站的功能吧,先來看看第一個方法的實現吧。

使用C# HttpHelper類來訪問網站

我先來說說我的思路吧,我事先設置一個關鍵字,如果通過抓來的網頁源代碼存在這個關鍵字的話就說明網站正常,否則就不正常,並寫文件做記錄

我們一起來看方法吧

首先來定義一個定時檢查器我設置時間 爲1分鐘檢查一次

        //定期類
        private System.Timers.Timer aTimer;

        /// <summary>
        /// 開啓服務時要執行的方法
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            aTimer = new System.Timers.Timer();
            //到達時間的時候執行事件;
            aTimer.Elapsed += new ElapsedEventHandler(timer1_Tick);
            // 設置引發時間的時間間隔 此處設置爲1秒(1000毫秒) 
            aTimer.Interval = 60 * 1000;
            //設置是執行一次(false)還是一直執行(true);
            aTimer.AutoReset = true;
            //是否執行System.Timers.Timer.Elapsed事件;
            aTimer.Enabled = true;
        }

具體的timer1_Tick實現如下

  /// <summary>
        /// 定時事件
        /// </summary>
        /// <param name="source">源對象</param>
        /// <param name="e">ElapsedEventArgs事件對象</param>
        protected void timer1_Tick(object source, ElapsedEventArgs e)
        {
            //幫助參考http://www.cnblogs.com/sufei/archive/2011/10/22/2221289.html
            HttpHelps objhh = new HttpHelps();
            //取網站源代碼
            string result = objhh.GetHttpRequestStringByNUll_Get("http://sufei.cnblogs.com", null);
            //看看查詢出來的網頁代碼是否存在Perky Su
            if (result.Contains("Perky Su"))
            {
                //如果存在我設置的關鍵字說明我的網站是正常的
                WriteFile("D:\\log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", 
                    "您監控的網站http://sufei.cnblogs.com正常監控時間 " + DateTime.Now.ToString() + "\r\n");
            }
            else
            {
                WriteFile("D:\\log\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", 
                    "您監控的網站http://sufei.cnblogs.com出現異常情況監控時間 "  + DateTime.Now.ToString() + "\r\n");
                //如果不存在說明我的網站是不正常的
            }
        }

        /// <summary>
        /// 寫文件
        /// </summary>
        /// <param name="_filePath">文件路徑</param>
        /// <param name="TOEXCELLR">要寫入的內容</param>
        private void WriteFile(string _filePath, string TOEXCELLR)
        {
            //檢查是否創建文檔成功
            if (CreateXmlFile(_filePath))
            {  //寫文本,
                using (StreamWriter fs = new StreamWriter(_filePath, true, System.Text.Encoding.UTF8))
                {
                    fs.Write(TOEXCELLR);
                }
            }
        }

        /// <summary>
        /// 創建文件 的方法
        /// </summary>
        /// <param name="filepath">路徑</param>
        /// <returns>文件存在返True否在爲False</returns>
        private static Boolean CreateXmlFile(string filepath)
        {
            try
            {
                //記錄成功時的記錄
                if (!File.Exists(filepath))
                {
                    using (StreamWriter xmlfs = new StreamWriter(filepath, true, System.Text.Encoding.UTF8))
                    {
                        xmlfs.Write("");
                    }
                    return true;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

這樣的話咱們的監控功能就算是實現了,

那麼再來處理兩個事件

    /// <summary>
        /// 停止服務時要執行的方法
        /// </summary>
        protected override void OnStop()
        {
            aTimer.Enabled = false;
        }

        /// <summary>
        /// 服務恢復時
        /// </summary>
        protected override void OnContinue()
        {
            aTimer.Enabled = true;
        }

好了咱們的監控程序算是大功告成了。

要怎麼才能安裝成爲服務程序呢?一起來看一下吧,首先我們一添加一個這樣的類

 [RunInstaller(true)]
    public partial class InstallerServices : System.Configuration.Install.Installer
    {
        /// <summary>
        /// 必需的設計器變量。
        /// </summary>
        private System.ComponentModel.Container components = null;
        private System.ServiceProcess.ServiceProcessInstaller spInstaller;
        private System.ServiceProcess.ServiceInstaller sInstaller;

        public InstallerServices()
        {
            // 該調用是設計器所必需的。
            InitializeComponent();
            // TODO: 在 InitComponent 調用後添加任何初始化
        }
        #region Component Designer generated code

        /// <summary>
        /// 設計器支持所需的方法 - 不要使用代碼編輯器修改
        /// 此方法的內容。
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
            // 創建ServiceProcessInstaller對象和ServiceInstaller對象
            this.spInstaller = new System.ServiceProcess.ServiceProcessInstaller();
            this.sInstaller = new System.ServiceProcess.ServiceInstaller();
            // 設定ServiceProcessInstaller對象的帳號、用戶名和密碼等信息
            this.spInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
            this.spInstaller.Username = null;
            this.spInstaller.Password = null;

            // 設定服務名稱服務程序的名稱
            this.sInstaller.ServiceName = "Jinakong";
            // 設定服務的啓動方式
            this.sInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
            this.Installers.AddRange(new System.Configuration.Install.Installer[] { this.spInstaller, this.sInstaller });

        }
        #endregion

    }

其實我們什麼也不需要做只需要把這個類放在這裏就行了,我們只要修改一個監控程序的服務名稱就行了。

現在我們生成一個項目 ,來安裝一下看看效果吧

安裝的時候我們需要用.net的一個Installer工具

直接進入.net命令行(VS2010命令行提示工具大家自己打開吧,不會的可以上網找一下,呵呵)

輸入如下

然後回車就行了

好了服務程序安裝好了,下面一起來啓動一下吧,開始程序輸入services.msc

如下圖


我們啓動後等上個五分鐘然後到我們事先設置好的日誌文件夾下面來看看是什麼效果 吧

如果我們的服務程序寫錯了,要修改怎麼辦呢?其實卸載的方法很簡單,只要在目錄前加上了/u就行了

如果真的修改了其實還是更簡單的方法,只要把服務停止 一下,然後覆蓋一下你安裝目錄下的文件就OK了。

不需要卸載服務的。

程序寫的比較簡單,只當入個門吧

程序下載地址:WindowsService.zip

-------------------------------------------------------------簽名部分您可以不訪問--------------------------------------------------------------

                         

         歡迎大家轉載,如有轉載請註明文章來自:   http://sufei.cnblogs.com/  

簽名:做一番一生引以爲豪的事業;在有生之年報答幫過我的人;並有能力幫助需要幫助的人;    

發佈了123 篇原創文章 · 獲贊 34 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章