首页 > 代码库 > Quartz.net 入门

Quartz.net 入门

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

使用方法

第一步:安装

Install-Package Common.LoggingInstall-Package Common.Logging.Log4Net1211Install-Package QuartzInstall-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= http://www.mamicode.com/"D:\App_Log\servicelog\CRM\"/>      <!--是否是向文件中追加日志-->      <param name= "AppendToFile" value= http://www.mamicode.com/"true"/>      <!--log保留天数-->      <param name= "MaxSizeRollBackups" value= http://www.mamicode.com/"10"/>      <!--日志文件名是否是固定不变的-->      <param name= "StaticLogFileName" value= http://www.mamicode.com/"false"/>      <!--日志文件名格式为:2008-08-31.log-->      <param name= "DatePattern" value= http://www.mamicode.com/"yyyy-MM-dd&quot;.read.log&quot;"/>      <!--日志根据日期滚动-->      <param name= "RollingStyle" value= http://www.mamicode.com/"Date"/>      <layout type="log4net.Layout.PatternLayout">        <param name="ConversionPattern" value=http://www.mamicode.com/"%d [%t] %-5p %c - %m%n %loggername" />      </layout>    </appender>        <!-- 控制台前台显示日志 -->    <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">      <mapping>        <level value=http://www.mamicode.com/"ERROR" />        <foreColor value=http://www.mamicode.com/"Red, HighIntensity" />      </mapping>      <mapping>        <level value=http://www.mamicode.com/"Info" />        <foreColor value=http://www.mamicode.com/"Green" />      </mapping>      <layout type="log4net.Layout.PatternLayout">        <conversionPattern value=http://www.mamicode.com/"%n%date{HH:mm:ss,fff} [%-5level] %m" />      </layout>      <filter type="log4net.Filter.LevelRangeFilter">        <param name="LevelMin" value=http://www.mamicode.com/"Info" />        <param name="LevelMax" value=http://www.mamicode.com/"Fatal" />      </filter>    </appender>    <root>      <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) -->      <level value=http://www.mamicode.com/"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=http://www.mamicode.com/"FILE-WATCH" />        <arg key="configFile" value=http://www.mamicode.com/"~/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 precedencequartz.scheduler.instanceName = QuartzTest# configure thread pool infoquartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartzquartz.threadPool.threadCount = 10quartz.threadPool.threadPriority = Normal# job initialization plugin handles our xml reading, without it defaults are usedquartz.plugin.xml.type = Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartzquartz.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

 

 

 

 

 

 

 

 

  

Quartz.net 入门