Quartz.NET 2.0 学习笔记(5) :实例创建Windows服务实现任务调度

Quartz.NET 项目地址 http://quartznet.sourceforge.net/

Quartz.NET 2.0 学习笔记(1) :Quartz.NET简介

Quartz.NET 2.0 学习笔记(2) :和1.0的几点不同

Quartz.NET 2.0 学习笔记(3) :通过配置文件实现任务调度

Quartz.NET 2.0 学习笔记(4) :cron表达式

Quartz.NET 2.0 学习笔记(5) :实例创建Windows服务实现任务调度

 

使用普通Windows服务创建Quartz.Net服务项目

  1. 首先创建Quartz.Net.2.0解决方案,添加 Windows服务 项目,添加安装程序,修改服务运行账户类型为LocalSystem(默认为User)
  2. 添加C5.dll、Common.Logging.dll、Common.Logging.Log4Net.dll、log4net.dll、Quartz.dll引用

    C5.dll 一个C#和其他CLI语言的泛型集合类。.Net2.0及以上才可以使用。简介地址:http://www.itu.dk/research/c5/
    Common.Logging.dll 通用日志接口
    Common.Logging.Log4Net.dll 提供log4net对通用日志接口(Common.Logging)的实现
    log4net.dll 小白都知道不解释

  3. 添加quartz.config文件 Quartz.Net的配置文件,并设置编译时生成到输出目录为始终复制
  4. Windows服务文件上右键查看代码,编写Quartz服务启动代码,重写OnStart、OnStop、OnPause、OnContinue方法,分别对应IScheduler的Start、Shutdown、PauseAll、ResumeAll方法,详见代码
    QuartzService.cs
    using System.ServiceProcess;
    
    using Common.Logging;
    
    using Quartz.Impl;
    
    
    
    namespace Quartz.Net.Service
    
    {
    
        public partial class QuartzService : ServiceBase
    
        {
    
            private readonly ILog logger;
    
            private IScheduler scheduler;
    
    
    
            public QuartzService()
    
            {
    
                InitializeComponent();
    
                logger = LogManager.GetLogger(GetType());
    
                ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
    
                scheduler = schedulerFactory.GetScheduler();
    
            }
    
    
    
            protected override void OnStart(string[] args)
    
            {
    
                scheduler.Start();
    
                logger.Info("Quartz服务成功启动");
    
            }
    
    
    
            protected override void OnStop()
    
            {
    
                scheduler.Shutdown();
    
                logger.Info("Quartz服务成功终止");
    
            }
    
    
    
            protected override void OnPause()
    
            {
    
                scheduler.PauseAll();
    
            }
    
    
    
            protected override void OnContinue()
    
            {
    
                scheduler.ResumeAll();
    
            }
    
          
    
        }
    
    }

     

至此Quarzt.Net 的Windows服务已成功创建,接下创建实现了IJob接口Quartz任务

  1. 添加Quartz.Net.Demo类库项目
  2. 添加Common.Logging.dll、log4net.dll、Quartz.dll的引用(实际项目中Common.Logging.dll和log4net.dll任意引用一个即可,此处为演示需要)
  3. 添加DemoJob1.cs,实现IJob接口,日志记录使用Common.Logging接口
    DemoJob1.cs
    using System;
    
    
    
    namespace Quartz.Net.Demo
    
    {
    
        /// <summary>
    
        /// 实现IJob接口
    
        /// </summary>
    
        public class DemoJob1 : IJob
    
        {
    
            //使用Common.Logging.dll日志接口实现日志记录
    
            private static readonly Common.Logging.ILog logger = Common.Logging.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
            #region IJob 成员
    
    
    
            public void Execute(IJobExecutionContext context)
    
            {
    
                try
    
                {
    
                    logger.Info("DemoJob1 任务开始运行");
    
    
    
                    for (int i = 0; i < 10; i++)
    
                    {
    
                        logger.InfoFormat("DemoJob1 正在运行{0}", i);
    
                    }
    
    
    
                    logger.Info("DemoJob1任务运行结束");
    
                }
    
                catch (Exception ex)
    
                {
    
                    logger.Error("DemoJob2 运行异常", ex);
    
                }
    
    
    
            }
    
    
    
            #endregion
    
        }
    
    }

     

  4. 添加DemoJob2.cs,实现IJob接口,日志记录使用log4net
    DemoJob2.cs
    using System;
    
    
    
    namespace Quartz.Net.Demo
    
    {
    
        /// <summary>
    
        /// 实现IJob接口
    
        /// </summary>
    
        public class DemoJob2 : IJob
    
        {
    
            //使用log4net.dll日志接口实现日志记录
    
            private static readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
            #region IJob 成员
    
    
    
            public void Execute(IJobExecutionContext context)
    
            {
    
                try
    
                {
    
                    logger.Info("DemoJob2 任务开始运行");
    
    
    
                    for (int i = 0; i < 10; i++)
    
                    {
    
                        logger.InfoFormat("DemoJob2 正在运行{0}", i);
    
                    }
    
    
    
                    logger.Info("DemoJob2任务运行结束");
    
                }
    
                catch (Exception ex)
    
                {
    
                    logger.Error("DemoJob2 运行异常", ex);
    
                }
    
    
    
            }
    
    
    
            #endregion
    
        }
    
    }

     

  5. 添加quartz_jobs.xml(配置调度任务)
    quartz_jobs.xml
    <?xml version="1.0" encoding="UTF-8"?>
    
    
    
    <!-- This file contains job definitions in schema version 2.0 format -->
    
    
    
    <job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0">
    
    
    
      <processing-directives>
    
        <overwrite-existing-data>true</overwrite-existing-data>
    
      </processing-directives>
    
    
    
      <schedule>
    
        <!--定义示例任务1 Job-->
    
        <job>
    
          <name>DemoJob1</name>
    
          <group>DeomJobGroup</group>
    
          <description>Quartz.Net示例任务1</description>
    
          <job-type>Quartz.Net.Demo.DemoJob1,Quartz.Net.Demo</job-type>
    
          <durable>true</durable>
    
          <recover>false</recover>
    
        </job>
    
    
    
        <!--定义示例任务2 Job-->
    
        <job>
    
          <name>DemoJob2</name>
    
          <group>DeomJobGroup</group>
    
          <description>Quartz.Net示例任务2</description>
    
          <job-type>Quartz.Net.Demo.DemoJob2,Quartz.Net.Demo</job-type>
    
          <durable>true</durable>
    
          <recover>false</recover>
    
        </job>
    
    
    
        <!--定义示例任务1 触发器 每30秒执行一次DemoJob1任务-->
    
        <trigger>
    
          <cron>
    
            <name>DemoJob1Trigger</name>
    
            <group>DeomJobTriggerGroup</group>
    
            <job-name>DemoJob1</job-name>
    
            <job-group>DeomJobGroup</job-group>
    
            <cron-expression>0/30 * * * * ?</cron-expression>
    
          </cron>
    
        </trigger>
    
    
    
        <!--定义示例任务2 触发器 每分钟执行一次DemoJob2任务-->
    
        <trigger>
    
          <cron>
    
            <name>DemoJob2Trigger1</name>
    
            <group>DeomJobTriggerGroup</group>
    
            <job-name>DemoJob2</job-name>
    
            <job-group>DeomJobGroup</job-group>
    
            <cron-expression>0 * * * * ?</cron-expression>
    
          </cron>
    
        </trigger>
    
    
    
        <!--定义示例任务2 触发器 每天凌晨01:00执行一次DemoJob2任务-->
    
        <trigger>
    
          <cron>
    
            <name>DemoJob2Trigger2</name>
    
            <group>DeomJobTriggerGroup</group>
    
            <job-name>DemoJob2</job-name>
    
            <job-group>DeomJobGroup</job-group>
    
            <cron-expression>0 0 1 * * ?</cron-expression>
    
          </cron>
    
        </trigger>
    
      </schedule>
    
    </job-scheduling-data>

     

  6. 修改app.config,配置Common.logging、log4net
    app.config
    <?xml version="1.0"?>
    
    <configuration>
    
      <configSections>
    
        <section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
    
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
    
        <sectionGroup name="common">
    
          <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging"/>
    
        </sectionGroup>
    
      </configSections>
    
      <common>
    
        <logging>
    
          <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net">
    
            <arg key="configType" value="INLINE"/>
    
          </factoryAdapter>
    
        </logging>
    
      </common>
    
      <log4net>
    
        <appender name="InfoFileAppender" type="log4net.Appender.RollingFileAppender">
    
          <file value="log/" />
    
          <appendToFile value="true" />
    
          <param name="DatePattern" value="yyyyMMdd&quot;.txt&quot;" />
    
          <rollingStyle value="Date" />
    
          <maxSizeRollBackups value="100" />
    
          <maximumFileSize value="1024KB" />
    
          <staticLogFileName value="false" />
    
          <Encoding value="UTF-8" />
    
          <filter type="log4net.Filter.LevelRangeFilter">
    
            <param name="LevelMin" value="INFO" />
    
            <param name="LevelMax" value="INFO" />
    
          </filter>
    
          <layout type="log4net.Layout.PatternLayout">
    
            <conversionPattern value="%date %-5level %logger  - %message%newline" />
    
          </layout>
    
        </appender>
    
        <appender name="ErrorFileAppender" type="log4net.Appender.RollingFileAppender">
    
          <file value="log/error.txt" />
    
          <appendToFile value="true" />
    
          <rollingStyle value="Size" />
    
          <maxSizeRollBackups value="100" />
    
          <maximumFileSize value="10240KB" />
    
          <staticLogFileName value="true" />
    
          <Encoding value="UTF-8" />
    
          <filter type="log4net.Filter.LevelRangeFilter">
    
            <param name="LevelMin" value="WARN" />
    
            <param name="LevelMax" value="FATAL" />
    
          </filter>
    
          <layout type="log4net.Layout.PatternLayout">
    
            <conversionPattern value="%date %-5level %logger - %message%newline" />
    
          </layout>
    
        </appender>
    
        <root>
    
          <level value="INFO" />
    
          <appender-ref ref="InfoFileAppender" />
    
          <appender-ref ref="ErrorFileAppender" />
    
        </root>
    
      </log4net>
    
    
    
      <!-- 
    
        We use quartz.config for this server, you can always use configuration section if you want to.
    
        Configuration section has precedence here.  
    
      -->
    
      <!--
    
      <quartz >
    
      </quartz>
    
      -->
    
      <startup>
    
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    
      </startup>
    
    </configuration>

     

Quartz.Net.Service和Quartz.Net.Demo均创建完毕后,进行编译然后把我们创建的Quartz服务添加到系统的服务中去

  1. 把编译好的如下文件拷贝到D:\QuartzService\ 
  2. 控制台下执行如下命令:sc create QuartzService binpath= D:\QuartzService\Quartz.Net.Service.exe 完成服务创建
  3. 启动QuartzService服务可以看到D:\QuartzService\的日志文件有如下输出
    View Code
    2012-04-15 08:10:28,391 INFO  Quartz.Impl.StdSchedulerFactory  - Quartz.NET properties loaded from configuration file 'D:\QuartzService\quartz.config'
    
    2012-04-15 08:10:28,438 INFO  Quartz.Impl.StdSchedulerFactory  - Using default implementation for object serializer
    
    2012-04-15 08:10:28,478 INFO  Quartz.Impl.StdSchedulerFactory  - Using default implementation for ThreadExecutor
    
    2012-04-15 08:10:28,498 INFO  Quartz.Core.SchedulerSignalerImpl  - Initialized Scheduler Signaller of type: Quartz.Core.SchedulerSignalerImpl
    
    2012-04-15 08:10:28,498 INFO  Quartz.Core.QuartzScheduler  - Quartz Scheduler v.2.0.0.400 created.
    
    2012-04-15 08:10:28,502 INFO  Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin  - Registering Quartz Job Initialization Plug-in.
    
    2012-04-15 08:10:28,517 INFO  Quartz.Simpl.RAMJobStore  - RAMJobStore initialized.
    
    2012-04-15 08:10:28,540 INFO  Quartz.Simpl.RemotingSchedulerExporter  - Registering remoting channel of type 'System.Runtime.Remoting.Channels.Tcp.TcpChannel' to port (555) with name (httpQuartz)
    
    2012-04-15 08:10:28,540 INFO  Quartz.Simpl.RemotingSchedulerExporter  - Remoting channel registered successfully
    
    2012-04-15 08:10:28,541 INFO  Quartz.Simpl.RemotingSchedulerExporter  - Successfully marhalled remotable scheduler under name 'QuartzScheduler'
    
    2012-04-15 08:10:28,543 INFO  Quartz.Core.QuartzScheduler  - Scheduler meta-data: Quartz Scheduler (v2.0.0.400) 'ServerScheduler' with instanceId 'NON_CLUSTERED'
    
      Scheduler class: 'Quartz.Core.QuartzScheduler' - access via remote incovation.
    
      NOT STARTED.
    
      Currently in standby mode.
    
      Number of jobs executed: 0
    
      Using thread pool 'Quartz.Simpl.SimpleThreadPool' - with 10 threads.
    
      Using job-store 'Quartz.Simpl.RAMJobStore' - which does not support persistence. and is not clustered.
    
    
    
    2012-04-15 08:10:28,543 INFO  Quartz.Impl.StdSchedulerFactory  - Quartz scheduler 'ServerScheduler' initialized
    
    2012-04-15 08:10:28,543 INFO  Quartz.Impl.StdSchedulerFactory  - Quartz scheduler version: 2.0.0.400
    
    2012-04-15 08:10:28,554 INFO  Quartz.Xml.XMLSchedulingDataProcessor  - Parsing XML file: D:\QuartzService\quartz_jobs.xml with systemId: ~/quartz_jobs.xml
    
    2012-04-15 08:10:28,930 INFO  Quartz.Xml.XMLSchedulingDataProcessor  - Adding 2 jobs, 3 triggers.
    
    2012-04-15 08:10:28,933 INFO  Quartz.Xml.XMLSchedulingDataProcessor  - Adding job: DeomJobGroup.DemoJob1
    
    2012-04-15 08:10:28,937 INFO  Quartz.Xml.XMLSchedulingDataProcessor  - Adding job: DeomJobGroup.DemoJob2
    
    2012-04-15 08:10:28,997 INFO  Quartz.Core.QuartzScheduler  - Scheduler ServerScheduler_$_NON_CLUSTERED started.
    
    2012-04-15 08:10:28,997 INFO  Quartz.Net.Service.QuartzService  - Quartz服务成功启动
    
    2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 任务开始运行
    
    2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行0
    
    2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行1
    
    2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行2
    
    2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行3
    
    2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行4
    
    2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行5
    
    2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行6
    
    2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行7
    
    2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行8
    
    2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行9
    
    2012-04-15 08:10:30,041 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1任务运行结束
    
    2012-04-15 08:11:00,002 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 任务开始运行
    
    2012-04-15 08:11:00,002 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行0
    
    2012-04-15 08:11:00,002 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行1
    
    2012-04-15 08:11:00,002 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行2
    
    2012-04-15 08:11:00,002 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行3
    
    2012-04-15 08:11:00,002 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行4
    
    2012-04-15 08:11:00,003 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行5
    
    2012-04-15 08:11:00,003 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行6
    
    2012-04-15 08:11:00,003 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行7
    
    2012-04-15 08:11:00,003 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行8
    
    2012-04-15 08:11:00,003 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行9
    
    2012-04-15 08:11:00,003 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1任务运行结束
    
    2012-04-15 08:11:00,003 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 任务开始运行
    
    2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行0
    
    2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行1
    
    2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行2
    
    2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行3
    
    2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行4
    
    2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行5
    
    2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行6
    
    2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行7
    
    2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行8
    
    2012-04-15 08:11:00,004 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2 正在运行9
    
    2012-04-15 08:11:00,005 INFO  Quartz.Net.Demo.DemoJob2  - DemoJob2任务运行结束
    
    2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 任务开始运行
    
    2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行0
    
    2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行1
    
    2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行2
    
    2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行3
    
    2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行4
    
    2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行5
    
    2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行6
    
    2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行7
    
    2012-04-15 08:11:29,999 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行8
    
    2012-04-15 08:11:30,000 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1 正在运行9
    
    2012-04-15 08:11:30,000 INFO  Quartz.Net.Demo.DemoJob1  - DemoJob1任务运行结束
    
    2012-04-15 08:11:32,607 INFO  Quartz.Core.QuartzScheduler  - Scheduler ServerScheduler_$_NON_CLUSTERED shutting down.
    
    2012-04-15 08:11:32,608 INFO  Quartz.Core.QuartzScheduler  - Scheduler ServerScheduler_$_NON_CLUSTERED paused.
    
    2012-04-15 08:11:32,611 INFO  Quartz.Simpl.RemotingSchedulerExporter  - Successfully disconnected remotable scheduler
    
    2012-04-15 08:11:32,612 INFO  Quartz.Core.QuartzScheduler  - Scheduler ServerScheduler_$_NON_CLUSTERED Shutdown complete.
    
    2012-04-15 08:11:32,612 INFO  Quartz.Net.Service.QuartzService  - Quartz服务成功终止

     

日志记录时可以根据需要使用Common.logging或者log4net,因为Quartz.Net使用的Common.logging的log4net实现,所以必须同时引用这两个dll,具体项目中引用这两个任意一个效果都是一样的(在使用log4net的前提下)

源文件下载:Quartz-2.0Demo.rar

PS:

有很多人问Quartz启动后,关闭服务时无法及时关闭,必须杀进程才可以,解决方法时在调用Shutdown方法时传入参数false,即不等待任务运行结束立即关闭

scheduler.Shutdown(false); 

你可能感兴趣的:(windows)