首页 后端开发 C#.Net教程 详细介绍Quartz.Net调度框架配置的实例

详细介绍Quartz.Net调度框架配置的实例

Jul 20, 2017 pm 04:21 PM
框架 调度

这篇文章主要为大家详细介绍了Quartz.Net调度框架的配置方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

在平时的工作中,估计大多数都做过轮询调度的任务,比如定时轮询数据库同步,定时邮件通知等等。大家通过windows计划任务,windows服务等都实现过此类任务,甚至实现过自己的配置定制化的框架。那今天就来介绍个开源的调度框架Quartz.Net(主要介绍配置的实现,因为有朋友问过此类问题)。调度的实现代码很简单,在源码中有大量Demo,这里就略过了。

Quartz.Net当前最新版本Quartz.NET 2.0 beta 1 Released

一、基于文件配置

先看一下简单的实现代码


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Quartz;
using Quartz.Impl;
using Common.Logging;

namespace Demo
{
 class Program
 {
  static void Main(string[] args)
  {
   
   // First we must get a reference to a scheduler
   ISchedulerFactory sf = new StdSchedulerFactory();
   IScheduler sched = sf.GetScheduler();
   
   sched.Start();   
   sched.Shutdown(true);
   
  }
 }
}
登录后复制

代码很简单,配置文件中的quartz基础配置,以及job,trigger信息是如何加载的?这个过程是发生 IScheduler sched = sf.GetScheduler();过程,主要体现在源码这一段


 public void Initialize()
  {
   // short-circuit if already initialized
   if (cfg != null)
   {
    return;
   }
   if (initException != null)
   {
    throw initException;
   }

   NameValueCollection props = (NameValueCollection) ConfigurationManager.GetSection("quartz");

   string requestedFile = Environment.GetEnvironmentVariable(PropertiesFile);
   string propFileName = requestedFile != null && requestedFile.Trim().Length > 0 ? requestedFile : "~/quartz.config";

   // check for specials
   propFileName = FileUtil.ResolveFile(propFileName);

   if (props == null && File.Exists(propFileName))
   {
    // file system
    try
    {
     PropertiesParser pp = PropertiesParser.ReadFromFileResource(propFileName);
     props = pp.UnderlyingProperties;
     Log.Info(string.Format("Quartz.NET properties loaded from configuration file '{0}'", propFileName));
    }
    catch (Exception ex)
    {
     Log.Error("Could not load properties for Quartz from file {0}: {1}".FormatInvariant(propFileName, ex.Message), ex);
    }

   }
   if (props == null)
   {
    // read from assembly
    try
    {
     PropertiesParser pp = PropertiesParser.ReadFromEmbeddedAssemblyResource("Quartz.quartz.config");
     props = pp.UnderlyingProperties;
     Log.Info("Default Quartz.NET properties loaded from embedded resource file");
    }
    catch (Exception ex)
    {
     Log.Error("Could not load default properties for Quartz from Quartz assembly: {0}".FormatInvariant(ex.Message), ex);
    }
   }
   if (props == null)
   {
    throw new SchedulerConfigException(
     @"Could not find <quartz> configuration section from your application config or load default configuration from assembly.
Please add configuration to your application config file to correctly initialize Quartz.");
   }
   Initialize(OverrideWithSysProps(props));
  }
登录后复制

通过上面代码分析,初始化首先会检查系统config中是否有 configuration section节点 (config指的app.config,web.config),如果系统config有quartz节点,则直接加载此处的配置信息。如果系统config没有quartz的基础配置信息,则会继续查找是否有quartz.config/Quartz.quartz.config 这两个配置文件的存在,如果有则加载配置信息,如果没有则扔出初始化配置异常。

而jobs.xml(调度的任务和触发器plugin节点配置文件)

app.config/web.config 中plugin配置


 <quartz>
  <add key="quartz.scheduler.instanceName" value="ExampleDefaultQuartzScheduler"/>
  <add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz"/>
  <add key="quartz.threadPool.threadCount" value="10"/>
  <add key="quartz.threadPool.threadPriority" value="2"/>
  <add key="quartz.jobStore.misfireThreshold" value="60000"/>
  <add key="quartz.jobStore.type" value="Quartz.Simpl.RAMJobStore, Quartz"/>
 <!--******************************Plugin配置********************************************* -->
 <add key="quartz.plugin.xml.type" value="Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz" />
 <add key="quartz.plugin.xml.fileNames" value="quartz_jobs.xml"/> 
 </quartz>
登录后复制

quartz.config 中plugin配置指向(quartz.plugin.xml.type / quartz.plugin.xml.fileNames)


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

quartz.scheduler.instanceName = ServerScheduler

# configure thread pool info
quartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartz
quartz.threadPool.threadCount = 10
quartz.threadPool.threadPriority = Normal

#--------------------------------*************plugin配置------------------------------------
# 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
登录后复制

二、基于代码的方式

这种情况直接通过代码实现的,官方DEMO很多都是如此,我们举个例子


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using Quartz;
using Quartz.Impl;
using System.Threading;
using Common.Logging;

namespace Demo
{
 class Program
 {
  static void Main(string[] args)
  {
   ILog log = LogManager.GetLogger(typeof(Demo.HelloJob));

   log.Info("------- Initializing ----------------------");

   // First we must get a reference to a scheduler
   ISchedulerFactory sf = new StdSchedulerFactory();
   IScheduler sched = sf.GetScheduler();

   log.Info("------- Initialization Complete -----------");


   //---------------------------------------代码添加job和trigger
   // computer a time that is on the next round minute
   DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

   log.Info("------- Scheduling Job -------------------");

   // define the job and tie it to our HelloJob class
   IJobDetail job = JobBuilder.Create<HelloJob>()
    .WithIdentity("job1", "group1")
    .Build();

   // Trigger the job to run on the next round minute
   ITrigger trigger = TriggerBuilder.Create()
    .WithIdentity("trigger1", "group1")
    .StartAt(runTime)
    .Build();

   // Tell quartz to schedule the job using our trigger
   sched.ScheduleJob(job, trigger);
   log.Info(string.Format("{0} will run at: {1}", job.Key, runTime.ToString("r")));

   // Start up the scheduler (nothing can actually run until the 
   // scheduler has been started)
   sched.Start();
   log.Info("------- Started Scheduler -----------------");

   // wait long enough so that the scheduler as an opportunity to 
   // run the job!
   log.Info("------- Waiting 65 seconds... -------------");

   // wait 65 seconds to show jobs
   Thread.Sleep(TimeSpan.FromSeconds(65));

   // shut down the scheduler
   log.Info("------- Shutting Down ---------------------");
   sched.Shutdown(true);
   log.Info("------- Shutdown Complete -----------------");
  }
 }
}
登录后复制

其实代码方式已经实现了和配置文件混搭的方式了。但是这种对方式是通过配置关联加载job与trigger配置,我们还有第三种方式,自己加载job与trigger配置文件。

三、手动加载配置文件


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; 
using Quartz;
using Quartz.Xml;
using Quartz.Impl;
using Quartz.Simpl;
using System.Threading;
using Common.Logging;
using System.IO;

namespace Demo
{
 class Program
 {
  static void Main(string[] args)
  {    
   XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper());
   ISchedulerFactory sf = new StdSchedulerFactory();
   IScheduler scheduler = sf.GetScheduler();

   Stream s = new StreamReader("~/quartz.xml").BaseStream;
   processor.ProcessStream(s, null);
   processor.ScheduleJobs(scheduler);

   scheduler.Start();
   scheduler.Shutdown();
   
  }
 }
}
登录后复制

亦或者这样 


using System.Text; 
using Quartz;
using Quartz.Xml;
using Quartz.Impl;
using Quartz.Simpl;
using System.Threading;
using Common.Logging;
using System.IO;

namespace Demo
{
 class Program
 {
  static void Main(string[] args)
  {    
   XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper());
   ISchedulerFactory sf = new StdSchedulerFactory();
   IScheduler scheduler = sf.GetScheduler();

   
   processor.ProcessFileAndScheduleJobs("~/quartz.xml",scheduler);
   
   scheduler.Start();
   scheduler.Shutdown();
   
  }
 }
}
登录后复制

目前根据源码分析大致就这几种配置方式,很灵活可以任意组合。 关于quartz的使用源码很详细,并且园子量有大量的学习文章。

记住quartz的配置读取方式首先app.config/web.config ---->quartz.config/Quartz.quartz.config ---->quartz_jobs.xml .

通过代码方式我们可以改变quartz_jobs.xml 的指向即自己新命名的xml文件  

(默认的quartz_jobs.xml是在XMLSchedulingDataProcessor.QuartzXmlFileName = "quartz_jobs.xml"被指定的)

方式一,通过quartz节点/quartz.config指向指定的jobs.xml。

方式二,通过XMLSchedulingDataProcessor 加载指定的jobs.xml 

以上是详细介绍Quartz.Net调度框架配置的实例的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1657
14
CakePHP 教程
1415
52
Laravel 教程
1309
25
PHP教程
1257
29
C# 教程
1231
24
如何评估Java框架商业支持的性价比 如何评估Java框架商业支持的性价比 Jun 05, 2024 pm 05:25 PM

评估Java框架商业支持的性价比涉及以下步骤:确定所需的保障级别和服务水平协议(SLA)保证。研究支持团队的经验和专业知识。考虑附加服务,如升级、故障排除和性能优化。权衡商业支持成本与风险缓解和提高效率。

PHP 框架的学习曲线与其他语言框架相比如何? PHP 框架的学习曲线与其他语言框架相比如何? Jun 06, 2024 pm 12:41 PM

PHP框架的学习曲线取决于语言熟练度、框架复杂性、文档质量和社区支持。与Python框架相比,PHP框架的学习曲线更高,而与Ruby框架相比,则较低。与Java框架相比,PHP框架的学习曲线中等,但入门时间较短。

Java框架的性能比较 Java框架的性能比较 Jun 04, 2024 pm 03:56 PM

根据基准测试,对于小型、高性能应用程序,Quarkus(快速启动、低内存)或Micronaut(TechEmpower优异)是理想选择。SpringBoot适用于大型、全栈应用程序,但启动时间和内存占用稍慢。

PHP 框架的轻量级选项如何影响应用程序性能? PHP 框架的轻量级选项如何影响应用程序性能? Jun 06, 2024 am 10:53 AM

轻量级PHP框架通过小体积和低资源消耗提升应用程序性能。其特点包括:体积小,启动快,内存占用低提升响应速度和吞吐量,降低资源消耗实战案例:SlimFramework创建RESTAPI,仅500KB,高响应性、高吞吐量

golang框架文档最佳实践 golang框架文档最佳实践 Jun 04, 2024 pm 05:00 PM

编写清晰全面的文档对于Golang框架至关重要。最佳实践包括:遵循既定文档风格,例如Google的Go编码风格指南。使用清晰的组织结构,包括标题、子标题和列表,并提供导航。提供全面准确的信息,包括入门指南、API参考和概念。使用代码示例说明概念和使用方法。保持文档更新,跟踪更改并记录新功能。提供支持和社区资源,例如GitHub问题和论坛。创建实际案例,如API文档。

如何为不同的应用场景选择最佳的golang框架 如何为不同的应用场景选择最佳的golang框架 Jun 05, 2024 pm 04:05 PM

根据应用场景选择最佳Go框架:考虑应用类型、语言特性、性能需求、生态系统。常见Go框架:Gin(Web应用)、Echo(Web服务)、Fiber(高吞吐量)、gorm(ORM)、fasthttp(速度)。实战案例:构建RESTAPI(Fiber),与数据库交互(gorm)。选择框架:性能关键选fasthttp,灵活Web应用选Gin/Echo,数据库交互选gorm。

Java框架学习路线图:不同领域中的最佳实践 Java框架学习路线图:不同领域中的最佳实践 Jun 05, 2024 pm 08:53 PM

针对不同领域的Java框架学习路线图:Web开发:SpringBoot和PlayFramework。持久层:Hibernate和JPA。服务端响应式编程:ReactorCore和SpringWebFlux。实时计算:ApacheStorm和ApacheSpark。云计算:AWSSDKforJava和GoogleCloudJava。

Golang框架学习过程中常见的误区有哪些? Golang框架学习过程中常见的误区有哪些? Jun 05, 2024 pm 09:59 PM

Go框架学习的误区有以下5种:过度依赖框架,限制灵活性。不遵循框架约定,代码难维护。使用过时库,带来安全和兼容性问题。过度使用包,混淆代码结构。忽视错误处理,导致意外行为和崩溃。

See all articles