Quartz:首先我贴出来了两段代码(下方),可以看出,首先会根据配置文件(quartz.config),包装出一个Quartz.Core.QuartzScheduler
instance,这是一个调度器,调度各个任务项(Jobs)的执行。这个调度器可以被Start、被Shutdown、被PauseAll、被ResumeAll,这对应
了windows服务的开启、停止、暂停、恢复。当启动服务,我就调用调度器的Start(),停止服务我就调用调度器的Shutdown()方法。
namespace QTDemo { public class ServiceRunner : ServiceControl, ServiceSuspend { private readonly IScheduler scheduler; public ServiceRunner() { scheduler = StdSchedulerFactory.GetDefaultScheduler(); } public bool Start(HostControl hostControl) { scheduler.Start(); return true; }
// 摘要: // An implementation of Quartz.ISchedulerFactory that does all of it's work // of creating a Quartz.Core.QuartzScheduler instance based on the contents // of a properties file. public class StdSchedulerFactory : ISchedulerFactory { public const string AutoGenerateInstanceId = "AUTO"; public const string ConfigurationSectionName = "quartz"; public const string DefaultInstanceId = "NON_CLUSTERED"; public const string PropertiesFile = "quartz.config";
那TopShelf又扮演了什么样的角色呢
这是一个宿主服务的框架。和ServiceBase、ServiceInstaller那一套的目的一样,都是用来创建Windows服务的。
1、新建项目控制台应用程序‘QTDemo’
2、从NuGet安装‘Quartz’,‘Topshelf’,‘Topshelf.Log4Net’
1 <?xml version="1.0" encoding="utf-8"?> 2 <packages> 3 <package id="Common.Logging" version="3.3.1" targetFramework="net45" /> 4 <package id="Common.Logging.Core" version="3.3.1" targetFramework="net45" /> 5 <package id="log4net" version="2.0.5" targetFramework="net45" /> 6 <package id="Quartz" version="2.3.3" targetFramework="net45" /> 7 <package id="Topshelf" version="3.3.1" targetFramework="net45" /> 8 <package id="Topshelf.Log4Net" version="3.3.1" targetFramework="net45" /> 9 </packages>
3、定义一个Job(一个任务项),继承Quartz.IJob
1 using Quartz; 2 namespace QTDemo.QuartzJobs 3 { 4 public sealed class TestJob : IJob 5 { 6 public void Execute(IJobExecutionContext context) 7 { 8 CommonHelper.AppLogger.InfoFormat("TestJob测试"); 9 10 } 11 } 12 } 13
4、配置(新建)quartz.config、quartz_jobs.xml
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