window Timers 定时服务

来源:互联网 发布:lol登录失败检查网络 编辑:程序博客网 时间:2024/06/15 01:28

原文:http://www.cnblogs.com/beijia/archive/2012/05/31/WinService.html

前段时间做过一个项目,前端系统提供添加定时任务,后端系统要时刻扫描数据库中的任务并进行相关操作。对于后端系统,首先想到的就是在Window服务中创建定时任务,于是参考了网上的一些资料,顺利完成。现将创建window service的步骤记录下来,方便以后回顾查看。

1、打开VS2008/VS2010,创建window服务项目 MyWindowService。

2、添加 window 服务项 MyService.cs ,代码如下:

View Code
复制代码
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 MyWindowService
{
    public partial class MyService : ServiceBase
    {
        System.Timers.Timer time = null// 定时器

        public MyService()
        {
            InitializeComponent(); // 在该方法中设置服务命名称:this.ServiceName = "MyService";

            time = new System.Timers.Timer();

            System.Collections.Specialized.NameValueCollection appSettings = System.Configuration.ConfigurationManager.AppSettings; // 获取配置文件信息

            int interval = 300000;

            if (appSettings["Interval"] != null)
            {
                if (!int.TryParse(appSettings["Interval"].ToString(), out interval))
                {
                    interval = 300000// 默认5分钟
                }
            }

            if (interval < 60000// 最短间隔1分钟
                interval = 6000;
            if (interval > 3600000// 最长间隔1小时
                interval = 3600000;

            time.Interval = interval; // 设置引发 Elapsed 事件间隔时间,单位毫秒

            time.AutoReset = true;

            time.Enabled = false// 指示引发 Elapsed 事件

            time.Elapsed += new System.Timers.ElapsedEventHandler(time_Elapsed);

            // 定时触发一个事件,如果不是定时触发,而是时刻都在运行可以使用protected override void OnStart(string[] args),和protected override void OnStop()两个方法表示启动和结束事件

            time.Start();
        }

        // 定时触发事件
        private void time_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            // 注意:Timer 的 Elapsed 事件每次触发都是新开一个线程
            
// 若要避免多个线程同时运行可能带来的问题,可以:1、将间隔设的尽量的长;2、在方法的开头和结尾分别加上以下代码 time.Enabled = false;和time.Enabled = true;

            
// to do
        }

        protected override void OnStart(string[] args)
        {
            // 设置引发 Elapsed 事件
            time.Enabled = true;
        }

        protected override void OnStop()
        {
            // 设置取消引发 Elapsed 事件
            time.Enabled = false;
        }
    }
}
复制代码


打开 MyService.cs 设计视图,右键选择“添加安装程序”,程序会默认为 MyService 服务创建安装程序类。

在 InitializeComponent() 方法中进行相关设置。


View Code 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
using System.Configuration.Install;
using System.ComponentModel;




namespace SinaWeiBoService
{
    [RunInstaller(true)]
    public class MyServiceInstaller: Installer
    {
        ServiceProcessInstaller processInstall;
        ServiceInstaller serviceInstall;
        public SinaServiceInstall()
        {
            this.processInstall = new ServiceProcessInstaller();
            this.serviceInstall = new ServiceInstaller();
            // this.serviceInstall.StartType = ServiceStartMode.Automatic;


            // 配置StartType 为 Automatic  (即自动启动)
            processInstall.Account = ServiceAccount.LocalSystem;
            this.serviceInstall.ServiceName = "MyService";
            this.Installers.Add(this.serviceInstall);
            this.Installers.Add(this.processInstall);


            // 或使用添加集合的方法


            // this.Installers.AddRange(new System.Configuration.Install.Installer[] { serviceInstall, processInstall });
        }


    }
}

5、项目编译成功后,打开vs命令工具,在系统中注册和卸载服务

注册服务:

C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\installutil  MyWindowService.exe

卸载服务:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil -u MyWindowService.exe

可以将以上两行代码放在一个cmd或bat类型的文件里,这样双击就可以了。

注册后进入服务就可以看到刚才创建的服务了


原创粉丝点击