Home >Backend Development >C#.Net Tutorial >Detailed introduction to Quartz.Net scheduling framework configuration examples
This article mainly introduces the configuration method of Quartz.Net scheduling framework in detail, which has certain reference value. Interested friends can refer to it
In daily work, it is estimated that most Most of them have done polling scheduling tasks, such as scheduled polling database synchronization, scheduled email notifications, etc. Everyone has implemented such tasks through Windows scheduled tasks, Windows services, etc., and even implemented their own customized configuration framework. So today I will introduce the open source scheduling framework Quartz.Net (mainly introducing the implementation of configuration, because a friend has asked such questions). The scheduling implementation code is very simple. There are a lot of demos in the source code, so I will skip them here.
The latest version of Quartz.Net, Quartz.NET 2.0 beta 1 Released
1. Based on file configuration
Let’s take a look at the simple implementation code first
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); } } }
The code is very simple. How are the quartz basic configuration in the configuration file, as well as job and trigger information loaded? This process occurs IScheduler sched = sf.GetScheduler();, which is mainly reflected in the source code section
##
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)); }Through the above code analysis, the initialization will first check the system Whether there is a 9b4c701a111f87c1cd1643746af7699b configuration section node in the config (config refers to app.config, web.config). If the system config has a quartz node, the configuration information here is directly loaded. If the system config does not have the basic configuration information of quartz, it will continue to look for the existence of the two configuration files quartz.config/Quartz.quartz.config. If there is, the configuration information will be loaded. If not, an initialization configuration exception will be thrown. And jobs.xml (scheduled task and trigger plugin node configuration file) app.config/web.config plugin configuration
<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>The plugin configuration in quartz.config points to (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
2. Based on The way of coding
This situation is realized directly through code. Many official DEMOs are like this. Let’s give an exampleusing 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 -----------------"); } } }In fact, the code The method has been implemented to mix and match with the configuration file. But this method is to load the job and trigger configuration through configuration association. We also have a third method, which is to load the job and trigger configuration files ourselves.
3. Manually load the configuration file
##
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(); } } }
Currently, based on source code analysis, there are roughly these configuration methods, which are very flexible and can be combined in any way. The source code for using quartz is very detailed, and there are a lot of learning articles in the garden.
Through code, we can change the point of quartz_jobs.xml to the newly named xml file (The default quartz_jobs.xml is specified in XMLSchedulingDataProcessor.QuartzXmlFileName = "quartz_jobs.xml") Method 1, point to the specified jobs.xml through quartz node/quartz.config. Method 2, load the specified jobs.xml through XMLSchedulingDataProcessor
The above is the detailed content of Detailed introduction to Quartz.Net scheduling framework configuration examples. For more information, please follow other related articles on the PHP Chinese website!