Windows服务摘要

       之前做一些需要定时处理的程序时,有放置在Global.asax文件的Application_Start方法中去处理。但最近发现这种写法非常不可靠。于是转为Windows服务来处理。
    一、Windows服务项目建立
        在Service1.cs的OnStart()和OnStop()方法中添加启动、关闭定时控制代码  

   protected override void OnStart(string[] args)
        {
            
int dealtime = Int32.Parse(ConfigurationManager.AppSettings["TimerValue"].Trim()); //单位小时
            timer1 = new System.Timers.Timer();
            timer1.Interval 
= 1000 * 60 * 60 * dealtime;
            timer1.Elapsed 
+= new System.Timers.ElapsedEventHandler(timer1_Elapsed);
            timer1.Enabled 
= true;
        }

        
protected override void OnStop()
        {
            
this.timer1.Enabled = false;
        }

 

 

    二、Windows服务参数设置

        打开Service1.cs "设计"选项卡,右键选择 "添加安装程序" ,则出现serviceInstaller1、serviceProcessInstaller1 2个组件;               

    serviceProcessInstaller1的Account属性设为"LocalSystem",serviceInstaller1的StartType属性设为"Automatic",同时也可设置DisplayName及Discription等

    三、Windosw服务批处理设置
        为简化安装和卸载服务操作,可以建立setup.bat、uninst.bat 这2个批处理:
        C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil 服务名.exe
        C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil /u 服务名.exe

    

    四、其它
      一些自定义的配置文件必须放在服务.exe所在的目录,比如自定义的XML、VNET.Config等,同时,在获取这些配置文件时,也必须用AppDomain.CurrentDomain.BaseDirectory 来获得,否则,服务启动后默认的运行目录是System32 。

posted on 2011-05-23 18:26  牦牛  阅读(982)  评论(5编辑  收藏  举报