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(命令行),

   4.0:cd C:WINDOWSMicrosoft.NETFrameworkv4.0.30319

     2.0:cd C:WINDOWSMicrosoft.NETFrameworkv2.0.50727

2、安装服务(项目生成的exe文件路径)

  InstallUtil "E:WindowsService1inDebugWindowsService1.exe"

3、卸载服务

  InstallUtil  /u "E:WindowsService1inDebugWindowsService1.exe"

四、查看window服务

    services.msc

控制面板-->管理工具-->服务,可在此手动启动,停止服务

五、调试window服务

1、通过【事件查看器】查看

2、直接在程序中调试(菜单-->调试-->附加进程-->服务名(这里的服务名是项目名称,不是ServiceName属性自定义的名称,所以建议自定义名称和项目名称保持一致,另外需勾选【显示所有用户的进程】才能看到服务名)-->附加

   这里附加的进程名应该是:WindowsService1.exe 而不是 WindowsService1.vshost.exe。WindowsService1.exe 默认不会出现,必须勾选【显示所有用户的进程】【显示所有会话中的进程】

3. 在程序中打断点调试即可,另外调试服务时服务必须已启动(管理工具-->服务)

原文地址:https://www.cnblogs.com/lpbca/p/5466400.html