.net 開發定時執行的windows服務


環境:win7+vs2010+Oracle11g+office2010(64位操作系統)

需求:開發定時執行的windows服務從數據庫中查詢數據下載到指定地址Excel中  

一、添加新建項目——windows——windows服務

在vs中自動生成如下文件:

本服務需要添加的引用如下圖:

 

1、文件Program.cs是應用程序的主入口點,有main方法指定進入方法Service1() :

        /// <summary>
        /// 應用程序的主入口點。
        /// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
   {
    new Service1()
   };
            ServiceBase.Run(ServicesToRun);
        }
    }

2、文件Service1.cs中有啟動,停止服務方法,可以在啟動方法中調用你自己寫的函數:

public Service1()         {             InitializeComponent();         }

        protected override void OnStart(string[] args)         {         }

        protected override void OnStop()         {         }

我的需求是定時執行,那就需要添加一個timer組件:

(1)可以在工具箱內拖拽

(2)在Service1.Designer.cs設計代碼中手動添加一個: private System.Timers.Timer timer;

我要靈活的設置執行時間,那就需要添加一個配置文件:

添加新建項目——Visual C#項——應用程序配置文件:

app.config文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

<appSettings>
    <add key="DBType" value="Oracle" />
    <!--下載Excel的時間,目前設置為每天23點執行一次-->
    <add key="StartTime" value="23:00:00"/>
  </appSettings>

<connectionStrings>//數據庫連接設置

 <add name="DefaultConnectionString" connectionString="Data Source=連接通配符;User ID=用戶名;Password=密碼;" providerName="System.Data.OracleClient"/>
  </connectionStrings>
</configuration>

3、在Service1.cs文件中添加timer事件方法:

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

   {            

    try     {                   

        //判斷當前時間是否是配置文件中服務要執行的時間       

        if (DateTime.Now.ToString("HH:mm:ss") == System.Configuration.ConfigurationSettings.AppSettings["StartTime"])                    

        { (sender as System.Timers.Timer).Interval = 23 * 60 * 60 * 1000.0;        //將時間間隔改為23小時,23小時后重新發生timer_Elapsed事件。                                                      ExcelFileDownload();  //服務所要做的主函數下載Excel(你的方法)              

        }                

        else                    

         (sender as System.Timers.Timer).Interval = 1000;//時間間隔為1秒。   

                }       

        catch (Exception ex)           

          {                 string err = ex.Message;            

         }        

 }

4、在Service1.Designer.cs文件InitializeComponent()方法中添加事件:

 private void InitializeComponent()
{

    this.timer = new System.Timers.Timer();
            ((System.ComponentModel.ISupportInitialize)(this.timer)).BeginInit();
            //
            // timer
            //
            this.timer.Enabled = true;
            this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
            //
            // Service2
            //
            this.ServiceName = "Service1";
            ((System.ComponentModel.ISupportInitialize)(this.timer)).EndInit();

 }

Service1.Designer.cs文件中方法如下圖:

 以上代碼方面基本完成,windows服務就要安裝到服務器上,要有安裝文件EXE;

項目生成之后,雙擊Service1.cs打開設計頁面后,右鍵,添加安裝程序,會產生文件ProjectInstaller.cs,如下圖:

雙擊ProjectInstaller.cs進入設計頁面會看到2個類似組件的東西,如圖:

分別右鍵——屬性,進行設置:

serviceInstaller1設置,啟動方式StartType,更改為Automatic;描述Description,最好填寫一下服務要做的工作;ServiceName可以更改,描述和ServiceName在服務器的服務處會看到;如圖設置:

serviceProcessInstaller1設置,把Account更改為LocalSystem,如圖設置:

添加安裝程序之后會在項目bin/debug 文件夾下產生WindowsServiceDownloadFile.exe等文件,這個就是安裝文件。

自此服務就算開發完成,如何進行測試,跟蹤

一、要把服務安裝到計算機上

1.在你的系統找到C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727下面的InstallUtil文件。
2.把這個文件復制到你的exe項目文件去。(bin/debug 文件夾)
3.點擊開始的運行,輸入cmd。
4.用cd 你要安裝服務器的文件路徑(具體……bin/debug 文件夾)
5.輸入installutil 你的服務名稱(包含.exe) ,installutil和你的服務名稱要加空格。
6.installutil 你的服務名稱(包含.exe) -u可以刪除服務。

安裝完成之后,要到計算機管理——服務和應用程序——服務中找到你的服務,手動啟動,之后就可以把服務附加到進程中進行debug跟蹤調試,不過比較麻煩的是,每次更改程序都要停止卸載服務重新安裝服務再進行調試。

注:如何生成windows服務安裝包在另一篇文章中詳細說明

注:如何從數據庫查詢數據下載到Excel中在另一篇文章中詳細說明


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM