Quartz.net通过配置文件来完成作业调度

简介:

将Quartz.NET集成到 Castle中 例子代码使用的Quartz.net版本是0.6,Quartz.NET 0.9 发布了 ,最新版本支持通过配置文件来完成后台的作业调度,不必手工创建Trigger和Scheduler。将QuartzStartable 改造如下:
using System;
using System.Collections.Generic;
using System.Text;
using Castle.Core;
using Quartz.Impl;
using Quartz;
using Common.Logging;
using System.Threading;
using System.IO;
using Quartz.Xml;
using System.Collections;
namespace QuartzComponent
{
    [Transient]
    public class QuartzStartable : IStartable
    {
        private ISchedulerFactory _schedFactory;
        private JobSchedulingDataProcessor processor;
        private static ILog log = LogManager.GetLogger(typeof(QuartzStartable));
        public QuartzStartable(ISchedulerFactory schedFactory)
        {
            _schedFactory = schedFactory;
            processor = new JobSchedulingDataProcessor(true, true);
        }
        public void Start()
        {
            log.Info("Starting service");
            IScheduler sched = _schedFactory.GetScheduler();
            //log.Info("------- Scheduling Jobs ----------------");
            //// jobs can be scheduled before sched.start() has been called
            //// get a "nice round" time a few seconds in the future...
            //DateTime ts = TriggerUtils.GetNextGivenSecondDate(null, 15);
            //// job1 will only fire once at date/time "ts"
            //JobDetail job = new JobDetail("job1", "group1", typeof(SimpleQuartzJob));
            //SimpleTrigger trigger = new SimpleTrigger("trigger1", "group1");
            //// set its start up time
            //trigger.StartTimeUtc = ts;
            //// set the interval, how often the job should run (10 seconds here) 
            //trigger.RepeatInterval = 10000;
            //// set the number of execution of this job, set to 10 times. 
            //// It will run 10 time and exhaust.
            //trigger.RepeatCount = 100;

            //// schedule it to run!
            //DateTime ft = sched.ScheduleJob(job, trigger);
            //log.Info(string.Format("{0} will run at: {1} and repeat: {2} times, every {3} seconds",
            //    job.FullName, ft.ToString("r"), trigger.RepeatCount, (trigger.RepeatInterval / 1000)));
            //log.Info("------- Waiting five minutes... ------------");
            //sched.Start();
            Stream s = ReadJobXmlFromEmbeddedResource("MinimalConfiguration.xml");
            processor.ProcessStream(s, null);
            processor.ScheduleJobs(new Hashtable(), sched, false);
            sched.Start();
            try
            {
                // wait five minutes to show jobs
                Thread.Sleep(300 * 1000);
                // executing...
            }
            catch (ThreadInterruptedException)
            {
            }

        }
        private static Stream ReadJobXmlFromEmbeddedResource(string resourceName)
        {
            string fullName = "QuartzComponent." + resourceName;
            return new StreamReader(typeof(QuartzStartable).Assembly.GetManifestResourceStream(fullName)).BaseStream;
        }
        public void Stop()
        {
            log.Info("Stopping service");
            try
            {
                IScheduler scheduler = _schedFactory.GetScheduler();
                scheduler.Shutdown(true);
            }
            catch (SchedulerException se)
            {
                log.Error("Cannot shutdown scheduler.", se);
            }
        }
    }
}
增加一个配置文件MinimalConfiguration.xml,设置为嵌入资源类型。内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<quartz xmlns=" [url]http://quartznet.sourceforge.net/JobSchedulingData[/url]"
        xmlns:xsi=" [url]http://www.w3.org/2001/XMLSchema-instance[/url]"
    version="1.0"
    overwrite-existing-jobs="true">
  
  <job>
  <job-detail>
   <name>jobName1</name>
   <group>jobGroup1</group>
   <job-type>QuartzComponent.SimpleQuartzJob, QuartzComponent</job-type>
  </job-detail>
   
  <trigger>
   <simple>
    <name>simpleName</name>
    <group>simpleGroup</group>
    <job-name>jobName1</job-name>
    <job-group>jobGroup1</job-group>
    <start-time>2007-12-09T18:08:50</start-time>
    <repeat-count>100</repeat-count>
    <repeat-interval>3000</repeat-interval>
   </simple>
      </trigger>
   <trigger>
    <cron>
     <name>cronName</name>
     <group>cronGroup</group>
     <job-name>jobName1</job-name>
     <job-group>jobGroup1</job-group>
     <start-time>1982-06-28T18:15:00+02:00</start-time>
     <cron-expression>0/10 * * * * ?</cron-expression>
    </cron>
   </trigger>
 </job>
</quartz>
可以看到,在配置文件中把jobdetail和trigger都作了完整的定义,并组合成一个job。
当然也可以在quartz.properties文件中设置一个quertz_job.xml文件,例如:
            // First we must get a reference to a scheduler
            NameValueCollection properties = new NameValueCollection();
            properties["quartz.scheduler.instanceName"] = "XmlConfiguredInstance";
            
            // set thread pool info
            properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
            properties["quartz.threadPool.threadCount"] = "5";
            properties["quartz.threadPool.threadPriority"] = "Normal";
            // job initialization plugin handles our xml reading, without it defaults are used
            properties["quartz.plugin.xml.type"] = "Quartz.Plugin.Xml.JobInitializationPlugin, Quartz";
            properties["quartz.plugin.xml.fileNames"] = "~/quartz_jobs.xml";
            ISchedulerFactory sf = new StdSchedulerFactory(properties);
这样,在启动Castle的时候,Quartz.Plugin.Xml.JobInitializationPlugin就会自动读取quartz.properties这个配置文件,并初始化调度信息,启动Scheduler。
一个Job类,一个quartz.properties文件,一个quertz_job.xml文件,非常简单灵活。
下载例子代码 : QuartzComponentWithXml.zip




本文转自 张善友 51CTO博客,原文链接:http://blog.51cto.com/shanyou/72928,如需转载请自行联系原作者
目录
相关文章
|
XML 存储 JSON
使用自定义XML配置文件在.NET桌面程序中保存设置
本文将详细介绍如何在.NET桌面程序中使用自定义的XML配置文件来保存和读取设置。除了XML之外,我们还将探讨其他常见的配置文件格式,如JSON、INI和YAML,以及它们的优缺点和相关的NuGet类库。最后,我们将重点介绍我们为何选择XML作为配置文件格式,并展示一个实用的示例。
124 0
|
NoSQL API 调度
.NET开源的轻量化定时任务调度,支持临时的延时任务和重复循环任务(可持久化) - FreeScheduler
.NET开源的轻量化定时任务调度,支持临时的延时任务和重复循环任务(可持久化) - FreeScheduler
176 0
|
23天前
|
监控 网络安全 调度
Quartz.Net整合NetCore3.1,部署到IIS服务器上后台定时Job不被调度的解决方案
解决Quartz.NET在.NET Core 3.1应用中部署到IIS服务器上不被调度的问题,通常需要综合考虑应用配置、IIS设置、日志分析等多个方面。采用上述策略,结合细致的测试和监控,可以有效地提高定时任务的稳定性和可靠性。在实施任何更改后,务必进行充分的测试,以验证问题是否得到解决,并监控生产环境的表现,确保长期稳定性。
35 1
|
5月前
|
SQL JavaScript NoSQL
.NET有哪些好用的定时任务调度框架
.NET有哪些好用的定时任务调度框架
101 1
|
JSON 数据格式
.net core 读取配置文件的几种方式
# 一、Json配置文件 ## 1、这里的配置文件指的是下图 ![请在此添加图片描述](https://developer-private-1258344699.cos.ap-guangzhou.myqcloud.com/column/article/5877188/20231031-c79281ce.png?x-cos-security-token=Agam0Cn5pDWzx5RjFFzmFp5SXifE2lwa11a1f9dbaeac346ddc3b179889543979Cq1MFNxd9AGUyz-E0xgqW-YuUxnToKOaIzGnWLMcgCmVO4YvDOI5Os41fWu
134 0
.net core 读取配置文件的几种方式
|
6月前
|
XML 开发框架 .NET
C#/ASP.NET应用程序配置文件app.config/web.config的增、删、改操作
C#/ASP.NET应用程序配置文件app.config/web.config的增、删、改操作
68 1
|
6月前
|
XML Java 数据格式
javaweb实训第五天下午——xml配置文件约束报错问题
问题描述: 如果电脑连不上网,或者网速不好可能会造成Spring框架中xml配置文件出现错误。但是这个错误不影响项目的运行的;
61 0
|
开发框架 前端开发 JavaScript
一个.Net简单、易用的配置文件操作库
一个.Net简单、易用的配置文件操作库
57 0
|
XML 存储 JSON
.Net Core基础之读取配置文件
.Net Core基础之读取配置文件
165 0
|
数据可视化 前端开发 IDE
江南大学物联网工程学院数据库课程实验三作业3vb.net实验报告
江南大学物联网工程学院数据库课程实验三作业3vb.net实验报告
145 1
江南大学物联网工程学院数据库课程实验三作业3vb.net实验报告
下一篇
无影云桌面