.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:WINDOWSMicrosoft.NETFrameworkv2.0.50727下面的InstallUtil文件。
2.把这个文件复制到你的exe项目文件去。(bin/debug 文件夹)
3.点击开始的运行,输入cmd。
4.用cd 你要安装服务器的文件路径(具体……bin/debug 文件夹)
5.输入installutil 你的服务名称(包含.exe) ,installutil和你的服务名称要加空格。
6.installutil 你的服务名称(包含.exe) -u可以删除服务。

安装完成之后,要到计算机管理——服务和应用程序——服务中找到你的服务,手动启动,之后就可以把服务附加到进程中进行debug跟踪调试,不过比较麻烦的是,每次更改程序都要停止卸载服务重新安装服务再进行调试。

注:如何生成windows服务安装包在另一篇文章中详细说明

注:如何从数据库查询数据下载到Excel中在另一篇文章中详细说明

原文地址:https://www.cnblogs.com/xuxin-1989/p/4024570.html