创建 window service 定时任务

参考文章:http://www.cnblogs.com/jack-liang/archive/2011/05/20/2051743.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;
        }
    }
}
复制代码

3、添加 window 服务 安装程序类 MyServiceInstaller.cs。

方法一:添加一个类 MyServiceInstaller 继承 Installer

代码如下:

 

复制代码
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 });
        }

    }
}
复制代码

方法二:

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

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

4、Program.cs 文件代码如下图:

复制代码
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace MyWindowService
{
    static class Program
    {
        /// <summary>
        
/// 应用程序的主入口点。
        
/// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                 new MyService() 
            };
            ServiceBase.Run(ServicesToRun);
        }
    }
}
复制代码

 

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

注册服务:

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

卸载服务:

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

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

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

 

posted @   贝加  阅读(1670)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示