• 创建 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 ,代码如下:

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

    代码如下:

    复制代码
    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 文件代码如下图:

    复制代码
    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:WINDOWSMicrosoft.NETFrameworkv2.0.50727installutil  MyWindowService.exe

    卸载服务:

    C:WINDOWSMicrosoft.NETFrameworkv2.0.50727installutil -u MyWindowService.exe

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

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

     

     
  • 相关阅读:
    JavaScript的作用域和块级作用域概念理解
    正则表达式中组的理解
    正则表达式的字符组取反(负值字符集合/范围)^必须出现在起始位置
    利用TortoiseGit(小乌龟)将项目上传至GitHub网站
    (.Net) NLog 记录日志功能
    关于网站中引用COM组件的部署问题
    备份与还原ORACLE数据库(通过CMD命令执行)
    C# Task中的Func, Action, Async与Await的使用
    ASP.NET WebAPI 项目示例(增删改查)
    .NET内存泄漏(之 静态事件)
  • 原文地址:https://www.cnblogs.com/love828/p/3330741.html
Copyright © 2020-2023  润新知