• Quartz.Net任务调度总结


    Quartz.Net使用经验总结:
    学习参考的例子不错,分享一下:
    (1)https://www.cnblogs.com/jys509/p/4628926.html,该博文介绍比较全面
    (2)https://www.cnblogs.com/abeam/p/8042531.html 该博文有关于任务调度及配置文件详细解释,很棒。
    (3)https://www.cnblogs.com/JentZhang/p/9597597.html 不错的学习例子
    (4)https://www.cnblogs.com/abeam/p/8042531.html :关于"使用 Topshelf 结合 Quartz.NET 创建 Windows 服务"的总结
    (5) https://www.jianshu.com/p/f5118bd69d34 :关于Quartz 2.x 与3.x版本差异分析不错

    第一步:新建控制台应用程序:QuartzJobDemo

    先直接看目录结构:

    第二步直接上源码:
    1.作业调度:ServiceRunner.cs源码
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    //using Common.Logging;//引用下面的吧
    using log4net;//_logger.InfoFormat("TestJob测试");  ---》为了输出,引用这个吧
    using Quartz;
    using Quartz.Impl;
    using Topshelf;
    
    namespace QuartzJobDemo.Services
    {
        public sealed class ServiceRunner: ServiceControl,ServiceSuspend
        {
            private readonly IScheduler _scheduler;
            private readonly ILog _logger = LogManager.GetLogger(typeof(TestJob));
    
            #region Quartz 2.X版本
            public ServiceRunner()
            {
                _scheduler = StdSchedulerFactory.GetDefaultScheduler();
            }
            #endregion
    
            #region Quartz 3.X版本
            //public ServiceRunner()
            //{
            //    scheduler = StdSchedulerFactory.GetDefaultScheduler().GetAwaiter().GetResult();
            //}
            #endregion
    
            public bool Start(HostControl hostControl)
            {
                _logger.InfoFormat(@"开始服务:{0}", DateTime.Now);
                _scheduler.Start();
                 return true;
            }
    
            public bool Stop(HostControl hostControl)
            {
                _logger.InfoFormat(@"停止服务:{0}", DateTime.Now);
                _scheduler.Shutdown(false);
                return true;
            }
    
            public bool Continue(HostControl hostControl)
            {
                _logger.InfoFormat(@"继续服务:{0}", DateTime.Now);
                _scheduler.ResumeAll();
                return true;
            }
    
            public bool Pause(HostControl hostControl)
            {
                _logger.InfoFormat(@"暂停服务:{0}", DateTime.Now);
                _scheduler.PauseAll();
                return true;
            }
        }
    }
    2.作业执行TestJob.cs源码
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    //using Common.Logging;//引用下面的吧
    using log4net;//_logger.InfoFormat("TestJob测试");  ---》为了输出,引用这个吧
    using Quartz;
    
    namespace QuartzJobDemo
    {
        public sealed class TestJob: IJob
        {
            private readonly ILog _logger = LogManager.GetLogger(typeof(TestJob));
    
            #region Quartz 2.X版本
            public void Execute(IJobExecutionContext context)
            {
                _logger.InfoFormat("TestJob测试");
            }
            #endregion
    
            #region Quartz 3.X版本
            //public Task Execute(IJobExecutionContext context)
            //{
            //    _logger.InfoFormat("TestJob测试");
            //    return Task.FromResult(true);
            //}
    
            /**
             * 重点问题是新的IJob实现Execute返回的是Task,老的是void,很多在使用的时候对于这个地方的返回不知道如何处理,看代码增加一行:
               return Task.FromResult(true);
             */
            #endregion
    
    
        }
    }
    
    3.主程序Program.cs源码:
    
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using QuartzJobDemo.Services;
    using Topshelf;
    
    namespace QuartzJobDemo
    {
        /**
     * 说明:学习地址:https://www.cnblogs.com/jys509/p/4628926.html
         *注意点 (1)
     * Quartz版本:2.6.1
     * TopShelf版本:3.0.2    TopShelf版本与 Topshelf.Log4Net版本最好一一对应!!!!!
     * Topshelf.Log4Net版本:3.0.2
         *注意点 (2)
         *三个配置文件的属性都是改为始终复制:quartz_jobs.xml  log4net.config     quartz.config
         * 关于配置文件的具体说明:https://www.cnblogs.com/abeam/p/8044460.html
         * 注意点(3)
         * TestJob.cs中还是引用: using log4net;不要引用using Common.Logging;
         *
         *这个学习地址: https://www.cnblogs.com/abeam/p/8042531.html 也可以看看!!!+
     */
        class Program
        {
            static void Main(string[] args)
            {
                log4net.Config.XmlConfigurator.ConfigureAndWatch(
                    new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));
                HostFactory.Run(x =>
                {
                    #region Quartz 2.X版本: 2.6.1
                    x.UseLog4Net();
    
                    x.Service<ServiceRunner>();
    
                    x.SetDescription("QuartzJobDemo服务描述");
                    x.SetDisplayName("QuartzJobDemo服务显示名称");
                    x.SetServiceName("QuartzJobDemo服务名称");
    
                    x.EnablePauseAndContinue();
                    #endregion
    
                    #region Quartz 2.X版本: 2.6.1
                    //x.UseLog4Net();
    
                    //x.Service<ServiceRunner>(s => {
                    //    s.ConstructUsing(name => new ServiceRunner());
                    //    s.WhenStarted((tc, hc) => tc.Start(hc));
                    //    s.WhenStopped((tc, hc) => tc.Stop(hc));
                    //});
    
                    //x.RunAsLocalService();
                    //x.StartAutomaticallyDelayed();
    
                    //x.SetDescription("TestQuartzJob");
                    //x.SetDisplayName("TestQuartzJob");
                    //x.SetServiceName("TestQuartzJob");
    
                    //x.EnablePauseAndContinue();
    
                    #endregion
                });
            }
        }
    }
    

    三个配置文件(自己手动创建即可)源码:
    附配置文件详解:

    4.log4net.config:
    
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
      </configSections>
    
      <log4net>
        <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
          <!--日志路径-->
          <param name= "File" value= "D:QuartzJobDemo_Logservicelog"/>
          <!--是否是向文件中追加日志-->
          <param name= "AppendToFile" value= "true"/>
          <!--log保留天数-->
          <param name= "MaxSizeRollBackups" value= "10"/>
          <!--日志文件名是否是固定不变的-->
          <param name= "StaticLogFileName" value= "false"/>
          <!--日志文件名格式为:2008-08-31.log-->
          <param name= "DatePattern" value= "yyyy-MM-dd&quot;.read.log&quot;"/>
          <!--日志根据日期滚动-->
          <param name= "RollingStyle" value= "Date"/>
          <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n %loggername" />
          </layout>
        </appender>
    
        <!-- 控制台前台显示日志 -->
        <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
          <mapping>
            <level value="ERROR" />
            <foreColor value="Red, HighIntensity" />
          </mapping>
          <mapping>
            <level value="Info" />
            <foreColor value="Green" />
          </mapping>
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%n%date{HH:mm:ss,fff} [%-5level] %m" />
          </layout>
    
          <filter type="log4net.Filter.LevelRangeFilter">
            <param name="LevelMin" value="Info" />
            <param name="LevelMax" value="Fatal" />
          </filter>
        </appender>
    
        <root>
          <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) -->
          <level value="all" />
          <appender-ref ref="ColoredConsoleAppender"/>
          <appender-ref ref="RollingLogFileAppender"/>
        </root>
      </log4net>
    </configuration>
    
    5.quartz.config: 这个虽然提示无效的text标记,没关系不影响
    
    # You can configure your scheduler in either <quartz> configuration section
      # or in quartz properties file
      # Configuration section has precedence
    
      quartz.scheduler.instanceName = QuartzJobDemo
    
      # configure thread pool info
      quartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartz
      quartz.threadPool.threadCount = 10
      quartz.threadPool.threadPriority = Normal
    
      # job initialization plugin handles our xml reading, without it defaults are used
      quartz.plugin.xml.type = Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz
      quartz.plugin.xml.fileNames = ~/quartz_jobs.xml
    
      # export this server to remoting context
      #quartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter, Quartz
      #quartz.scheduler.exporter.port = 555
      #quartz.scheduler.exporter.bindName = QuartzScheduler
      #quartz.scheduler.exporter.channelType = tcp
      #quartz.scheduler.exporter.channelName = httpQuartz
    
    6.quartz_job.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>
    
        <!--TestJob测试 任务配置-->
        <job>
          <name>TestJob</name>
          <group>Test</group>
          <description>TestJob测试</description>
          <job-type>QuartzJobDemo.TestJob,QuartzJobDemo</job-type><!--命名空间.作业名,命名空间-->
          <!--<job-type>QuartzJobDemo.QuartzJobs.TestJob,QuartzJobDemo</job-type>-->
          <durable>true</durable>
          <recover>false</recover>
        </job>
        <trigger>
          <cron>
            <name>TestJobTrigger</name>
            <group>Test</group>
            <job-name>TestJob</job-name>
            <job-group>Test</job-group>
            <start-time>2019-12-20T00:00:00+08:00</start-time>
            <cron-expression>0/1 * * * * ?</cron-expression>
          </cron>
        </trigger>
    
      </schedule>
    </job-scheduling-data>
    
    

    附:配置文件详解:转自:https://www.cnblogs.com/abeam/p/8044460.html,博主总结很好(博主总结的另一篇关于任务调度的例子也很适合学习:https://www.cnblogs.com/abeam/p/8042531.html)
    直接截图吧,搞一天累了:




  • 相关阅读:
    1250. Check If It Is a Good Array
    380. Insert Delete GetRandom O(1)
    378. Kth Smallest Element in a Sorted Matrix
    341. Flatten Nested List Iterator
    387. First Unique Character in a String
    454. 4Sum II
    D
    勇敢的妞妞 ( 状压 + 思维)
    P1879 [USACO06NOV]玉米田Corn Fields (状压dp入门)
    G
  • 原文地址:https://www.cnblogs.com/newcapecjmc/p/12078094.html
Copyright © 2020-2023  润新知