首页 > 代码库 > Quartz.Net简单使用

Quartz.Net简单使用

Quartz.Net为开源的作业调度框架,使用方便,实现IJob接口,及相关配置,即可实现调度。

项目包安装:

install-package Quartz

install-package log4net

install-package Common.Logging.Log4Net1211(最新版为Common.Logging.Log4Net1213,但会出现“Unable to create instance of type Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter.”异常)

配置文件:

App.config

技术分享
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <configuration>
 3     <startup> 
 4         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
 5     </startup>
 6   <runtime>
 7     <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
 8       <dependentAssembly>
 9         <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
10         <bindingRedirect oldVersion="0.0.0.0-1.2.15.0" newVersion="1.2.15.0" />
11       </dependentAssembly>
12     </assemblyBinding>
13   </runtime>
14 </configuration>
View Code

log4net.config

技术分享
 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <configuration>
 3   <configSections>
 4     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
 5   </configSections>
 6 
 7   <log4net>
 8     <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
 9       <!--日志路径-->
10       <param name= "File" value= http://www.mamicode.com/"D:\QuartzLog\"/>
11       <!--是否是向文件中追加日志-->
12       <param name= "AppendToFile" value= http://www.mamicode.com/"true"/>
13       <!--log保留天数-->
14       <param name= "MaxSizeRollBackups" value= http://www.mamicode.com/"10"/>
15       <!--日志文件名是否是固定不变的-->
16       <param name= "StaticLogFileName" value= http://www.mamicode.com/"false"/>
17       <!--日志文件名格式为:2008-08-31.log-->
18       <param name= "DatePattern" value= http://www.mamicode.com/"yyyy-MM-dd&quot;.read.log&quot;"/>
19       <!--日志根据日期滚动-->
20       <param name= "RollingStyle" value= http://www.mamicode.com/"Date"/>
21       <layout type="log4net.Layout.PatternLayout">
22         <param name="ConversionPattern" value=http://www.mamicode.com/"%d [%t] %-5p %c - %m%n %loggername" />
23       </layout>
24     </appender>
25 
26     <!-- 控制台前台显示日志 -->
27     <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
28       <mapping>
29         <level value=http://www.mamicode.com/"ERROR" />
30         <foreColor value=http://www.mamicode.com/"Red, HighIntensity" />
31       </mapping>
32       <mapping>
33         <level value=http://www.mamicode.com/"Info" />
34         <foreColor value=http://www.mamicode.com/"Green" />
35       </mapping>
36       <layout type="log4net.Layout.PatternLayout">
37         <conversionPattern value=http://www.mamicode.com/"%n%date{HH:mm:ss,fff} [%-5level] %m" />
38       </layout>
39 
40       <filter type="log4net.Filter.LevelRangeFilter">
41         <param name="LevelMin" value=http://www.mamicode.com/"Info" />
42         <param name="LevelMax" value=http://www.mamicode.com/"Fatal" />
43       </filter>
44     </appender>
45 
46     <root>
47       <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) -->
48       <level value=http://www.mamicode.com/"all" />
49       <appender-ref ref="ColoredConsoleAppender"/>
50       <appender-ref ref="RollingLogFileAppender"/>
51     </root>
52   </log4net>
53 </configuration>
View Code

quartz.config

技术分享
 1 # You can configure your scheduler in either <quartz> configuration section
 2 # or in quartz properties file
 3 # Configuration section has precedence
 4 
 5 quartz.scheduler.instanceName = QuartzTest
 6 
 7 # configure thread pool info
 8 quartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartz
 9 quartz.threadPool.threadCount = 10
10 quartz.threadPool.threadPriority = Normal
11 
12 # job initialization plugin handles our xml reading, without it defaults are used
13 quartz.plugin.xml.type = Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz
14 quartz.plugin.xml.fileNames = ~/quartz_jobs.xml
15 
16 # export this server to remoting context
17 #quartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter, Quartz
18 #quartz.scheduler.exporter.port = 555
19 #quartz.scheduler.exporter.bindName = QuartzScheduler
20 #quartz.scheduler.exporter.channelType = tcp
21 #quartz.scheduler.exporter.channelName = httpQuartz
View Code

quartz_jobs.xml

技术分享
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 
 3 <!-- This file contains job definitions in schema version 2.0 format -->
 4 
 5 <job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0">
 6 
 7   <processing-directives>
 8     <overwrite-existing-data>true</overwrite-existing-data>
 9   </processing-directives>
10 
11   <schedule>
12 
13     <!--TestJob测试 任务配置-->
14     <job>
15       <name>TestJob</name>
16       <group>Test</group>
17       <description>TestJob测试</description>
18       <job-type>ConsoleApplicationQuartz.TestJob,ConsoleApplicationQuartz</job-type>
19       <durable>true</durable>
20       <recover>false</recover>
21     </job>
22     <trigger>
23       <cron>
24         <name>TestJobTrigger</name>
25         <group>Test</group>
26         <job-name>TestJob</job-name>
27         <job-group>Test</job-group>
28         <start-time>2015-01-22T00:00:00+08:00</start-time>
29         <cron-expression>0/3 * * * * ?</cron-expression>
30       </cron>
31     </trigger>
32 
33   </schedule>
34 </job-scheduling-data>
View Code

一、控制台项目:

创建Job类实现IJob接口

技术分享
 1 using log4net;
 2 using Quartz;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 
 9 namespace ConsoleApplicationQuartz
10 {
11     public sealed class TestJob : IJob
12     {
13         private readonly ILog _logger = LogManager.GetLogger(typeof(TestJob));
14         public void Execute(IJobExecutionContext context)
15         {
16             _logger.InfoFormat("TestJob测试");
17         }
18     }
19 }
View Code

Program主程序

技术分享
 1 using log4net;
 2 using Quartz;
 3 using Quartz.Impl;
 4 using System;
 5 using System.Collections.Generic;
 6 using System.IO;
 7 using System.Linq;
 8 using System.Text;
 9 using System.Threading.Tasks;
10 
11 namespace ConsoleApplicationQuartz
12 {
13     class Program
14     {
15         static void Main(string[] args)
16         {
17             log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));
18 
19             ILog log = LogManager.GetLogger(typeof(Program));
20             
21             StdSchedulerFactory factory = new StdSchedulerFactory();
22             IScheduler _scheduler = factory.GetScheduler();
23             _scheduler.Start();
24             Console.WriteLine("Start...");
25 
26             Console.Read();
27 
28             _scheduler.Shutdown();
29             Console.WriteLine("end...");
30             Console.Read();
31 
32         }
33     }
34 }
View Code

运行效果:

技术分享

ConsoleApplicationQuartz.TestJob - TestJob测试
 ConsoleApplicationQuartz.TestJobname2016-11-23 15:29:30,012 [QuartzTest_Worker-2] INFO  ConsoleApplicationQuartz.TestJob - TestJob测试
 ConsoleApplicationQuartz.TestJobname2016-11-23 15:29:33,007 [QuartzTest_Worker-3] INFO  ConsoleApplicationQuartz.TestJob - TestJob测试
 ConsoleApplicationQuartz.TestJobname2016-11-23 15:29:36,005 [QuartzTest_Worker-4] INFO  ConsoleApplicationQuartz.TestJob - TestJob测试
 ConsoleApplicationQuartz.TestJobname2016-11-23 15:29:39,012 [QuartzTest_Worker-5] INFO  ConsoleApplicationQuartz.TestJob - TestJob测试
 ConsoleApplicationQuartz.TestJobname2016-11-23 15:29:42,007 [QuartzTest_Worker-6] INFO  ConsoleApplicationQuartz.TestJob - TestJob测试
 ConsoleApplicationQuartz.TestJobname2016-11-23 15:29:45,002 [QuartzTest_Worker-7] INFO  ConsoleApplicationQuartz.TestJob - TestJob测试
 ConsoleApplicationQuartz.TestJobname2016-11-23 15:29:48,012 [QuartzTest_Worker-8] INFO  ConsoleApplicationQuartz.TestJob - TestJob测试
 ConsoleApplicationQuartz.TestJobname2016-11-23 15:29:51,002 [QuartzTest_Worker-9] INFO  ConsoleApplicationQuartz.TestJob - TestJob测试
 ConsoleApplicationQuartz.TestJobname2016-11-23 15:29:54,002 [QuartzTest_Worker-10] INFO  ConsoleApplicationQuartz.TestJob - TestJob测试
 ConsoleApplicationQuartz.TestJobname2016-11-23 15:32:25,981 [16] INFO  

二、Windows服务程序

创建IJob任务实现类

技术分享
 1 using log4net;
 2 using Quartz;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 
 9 namespace FD.ScheduleQuartz.WindowsServiceQuartz
10 {
11     public class TestJob : IJob
12     {
13         private static readonly ILog Logger = LogManager.GetLogger("TestJob");
14         public void Execute(IJobExecutionContext context)
15         {
16             string jobDes = context.JobDetail.Description;
17             Logger.Info(jobDes + "运行");
18         }
19     }
20 }
View Code

MainService主服务类

技术分享
 1 using log4net;
 2 using Quartz;
 3 using Quartz.Impl;
 4 using System;
 5 using System.Collections.Generic;
 6 using System.ComponentModel;
 7 using System.Data;
 8 using System.Diagnostics;
 9 using System.IO;
10 using System.Linq;
11 using System.ServiceProcess;
12 using System.Text;
13 using System.Threading.Tasks;
14 
15 namespace FD.ScheduleQuartz.WindowsServiceQuartz
16 {
17     public partial class MainService : ServiceBase
18     {
19         #region 字段
20         // 日志记录
21         private readonly ILog _logger;
22         // 调试器
23         private readonly IScheduler _scheduler;
24         #endregion
25 
26         public MainService()
27         {
28             InitializeComponent();
29 
30             log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"));
31 
32             _logger = LogManager.GetLogger(GetType());
33             StdSchedulerFactory factory = new StdSchedulerFactory();
34             _scheduler = factory.GetScheduler();
35         }
36 
37         protected override void OnStart(string[] args)
38         {
39             _scheduler.Start();
40             _logger.Info("服务启动");
41         }
42 
43         protected override void OnStop()
44         {
45             if (!_scheduler.IsShutdown)
46                 _scheduler.Shutdown();
47             _logger.Info("服务停止");
48         }
49 
50         protected override void OnPause()
51         {
52             _scheduler.PauseAll();
53             base.OnPause();
54         }
55 
56         protected override void OnContinue()
57         {
58             _scheduler.ResumeAll();
59             base.OnContinue();
60         }
61     }
62 }
View Code

修改quartz_jobs.xml中配置

将job-type修改为windows服务项目中类型

<job-type>FD.ScheduleQuartz.WindowsServiceQuartz.TestJob,WindowsServiceQuartz</job-type>

创建Windows服务的ProjectInstaller,并设置相应的服务名称及显示名称,运行此服务账号类型(LocalSystem),启动此服务方式和时间设置为Manual

编码后:通过:C:\Windows\Microsoft.NET\Framework64\v4.0.30319\下的installUtil.exe安装Windows服务

如图:技术分享

启动,及停止服务后,得到log内容:

FD.ScheduleQuartz.WindowsServiceQuartz.MainService - 服务启动
 FD.ScheduleQuartz.WindowsServiceQuartz.MainServicename2016-11-23 16:03:53,206 [QuartzTest_Worker-1] INFO  TestJob - TestJob测试运行
 TestJobname2016-11-23 16:03:54,002 [QuartzTest_Worker-2] INFO  TestJob - TestJob测试运行
 TestJobname2016-11-23 16:03:57,012 [QuartzTest_Worker-3] INFO  TestJob - TestJob测试运行
 TestJobname2016-11-23 16:04:00,015 [QuartzTest_Worker-4] INFO  TestJob - TestJob测试运行
 TestJobname2016-11-23 16:04:03,000 [QuartzTest_Worker-5] INFO  TestJob - TestJob测试运行
 TestJobname2016-11-23 16:04:06,010 [QuartzTest_Worker-6] INFO  TestJob - TestJob测试运行
 TestJobname2016-11-23 16:04:09,006 [QuartzTest_Worker-7] INFO  TestJob - TestJob测试运行
 TestJobname2016-11-23 16:04:12,011 [QuartzTest_Worker-8] INFO  TestJob - TestJob测试运行
 TestJobname2016-11-23 16:04:15,011 [QuartzTest_Worker-9] INFO  TestJob - TestJob测试运行
 TestJobname2016-11-23 16:04:18,011 [QuartzTest_Worker-10] INFO  TestJob - TestJob测试运行
 TestJobname2016-11-23 16:04:21,006 [QuartzTest_Worker-1] INFO  TestJob - TestJob测试运行
 TestJobname2016-11-23 16:04:21,404 [17] INFO  FD.ScheduleQuartz.WindowsServiceQuartz.MainService - 服务停止
 FD.ScheduleQuartz.WindowsServiceQuartz.MainServicename

 

Quartz.Net简单使用