Quartz.net 入门

Quartz.NET是一个开源的作业调度框架,允许我们快速的开发定时作业程序。

使用方法

第一步:安装

Install-Package Common.Logging
Install-Package Common.Logging.Log4Net1211
Install-Package Quartz
Install-Package Topshelf.Log4Net

Quartz依赖Common.Logging,又因为Log4Net是比较标准的日志工具,因此我们一般都会安装Common.Logging.Log4Net1211,另外定时作业一般都允许在后台服务中,因此我们也安装了Topshelf.Log4Net

注意:安装顺序不能乱,否则出现一些Log4Net版本不兼容问题

第二步:实现Job

using log4net;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzTest
{
    public sealed class HelloJob : IJob
    {
        private static ILog Logger = LogManager.GetLogger(typeof(Program));

        public void Execute(IJobExecutionContext context)
        {
            Logger.Info(DateTime.Now);
        }
    }

}

第三步:使用Topshelf调度任务,QuartzRunner.cs

using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Topshelf;

namespace QuartzTest
{
    public class QuartzRunner : ServiceControl, ServiceSuspend
    {
        private IScheduler scheduler;

        public bool Start(HostControl hostControl)
        {
            scheduler = StdSchedulerFactory.GetDefaultScheduler();

            scheduler.Start();

            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            scheduler.Shutdown(false);

            return true;
        }

        public bool Continue(HostControl hostControl)
        {
            scheduler.ResumeAll();

            return true;
        }

        public bool Pause(HostControl hostControl)
        {
            scheduler.PauseAll();

            return true;
        }
    }

}

第四步:程序入口
Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Topshelf;

namespace QuartzTest
{
    class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                x.UseLog4Net("~/log4net.config");

                x.Service<QuartzRunner>();

                x.SetDescription("QuartzTest");
                x.SetDisplayName("QuartzTest");
                x.SetServiceName("QuartzTest");

                x.EnablePauseAndContinue();
            });
        }

    }
}

第五步:新建一个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:\App_Log\servicelog\CRM\"/>
      <!--是否是向文件中追加日志-->
      <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>

第六步:在App.config里配置一下日志输出,增加在 configuration 节点下

  <configSections>
    <sectionGroup name="common">
      <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
    </sectionGroup>
  </configSections>

  <common>
    <logging>
      <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net1211">
        <arg key="configType" value="FILE-WATCH" />
        <arg key="configFile" value="~/log4net.config" />
      </factoryAdapter>
    </logging>
  </common>

第七步:配置Quartz

quartz_jobs.xml

# You can configure your scheduler in either <quartz> configuration section
# or in quartz properties file
# Configuration section has precedence

quartz.scheduler.instanceName = QuartzTest

# 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

quartz_jobs.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>
    <job>
      <name>HelloJob</name>
      <group>Demo</group>
      <description>显示当前时间。</description>
      <job-type>QuartzTest.HelloJob, QuartzTest</job-type>
      <durable>true</durable>
      <recover>false</recover>
    </job>
    <trigger>
      <cron>
        <name>DemoTrigger</name>
        <group>Demo</group>
        <job-name>HelloJob</job-name>
        <job-group>Demo</job-group>
        <start-time>2013-10-25T00:00:00+08:00</start-time>
        <cron-expression>0/2 * * * * ?</cron-expression>
      </cron>
    </trigger>
  </schedule>
</job-scheduling-data>

整体框架目录图如下:

 

 

 最后:

编译、Release 生成。把 Release 文件夹 Copy 到 C 盘

编译、Release 生成。把 Release 文件夹 Copy 到 C 盘

安装:SampleWindowsService.exe install
启动:SampleWindowsService.exe start
卸装:SampleWindowsService.exe uninstall

 

 

 

 

 

 

 

 

  

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。