Simple and practical framework of regular tasks of Quartz.NET

Simple and practical framework of regular tasks of Quartz.NET


Park blog articles Id: 12659890


Quartz .NET

Overview:

Quartz .NET is an open source job scheduling framework, ideally suited in the daily work, the timing polling database synchronization, the timing of the notification message, processing the timing data.

  • Timing database synchronization.
  • The timing of the notification.
  • Processing the timing data.

Quartz .NET allows developers to schedule jobs time interval (or days) in accordance with. It implements many relationships and triggers the job, but also to multiple jobs associated with different triggers. The integration of Quartz .NET applications can reuse jobs from different events, one event can also combine multiple jobs.

Next we have to create a simple example to illustrate the application of Quartz .NET timing tasks, and probably steps are divided into the following steps:

  1. We need to write a class to implement certain tasks need to be timed execution.
  2. Create a timer for scheduling task scheduler.
  3. By JobBuildergenerating a task Job.
  4. By TriggerBuildercreating a trigger Trigger.
  5. Job Instance create and Trigger instances added to the scheduler Scheduler.

Before writing Demo, we need to make some preparations:

In Visual Studio, we NuGet through the package manager, you need to install the Quartz package, where we installed the 2.5.0 version, the command is as follows:

Install-Package Quartz -Version 2.5.0

In the following examples, the following main need to use three dll assemblies.

  • Common.Logging.dll
  • Common.Logging.Core.dll
  • Quartz.dll

NuGet the above command, the program has three sets we need to download the current project.

Use Code ways:

The following sample code is:

To create a job for a specific task to achieve:

using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzTest
{
    /// <summary>
    /// 用于演示需要定时执行的任务
    /// </summary>
    class DemoJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            Console.WriteLine(string.Format("Exceute Job : 执行时间:{0}", DateTime.Now.ToString()));
        }
    }
}

Create a specific implementation of triggers:

using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzTest
{
    /// <summary>
    /// 调度器
    /// </summary>
    class DemoScheule
    {
        public static void Start()
        {
            /*------Demo1 无参数 简单调用的方法 -----------*/

            //实例化调度器工厂
            ISchedulerFactory schedulefactory = new StdSchedulerFactory();

            //通过调度工厂获取一个调度器对象
            IScheduler scheduler = schedulefactory.GetScheduler();

            //启动调度器
            scheduler.Start();

            //创建一个定时任务作业
            IJobDetail job1 = JobBuilder.Create<DemoJob>().WithIdentity("DemoJob","groupa").Build();

            //创建一个触发器
            ITrigger trigger1 = TriggerBuilder
                .Create()
                .WithIdentity("DemoTrigger","groupa")
                .StartNow()                                 //设置每五秒执行一次,无限循环执行
                .WithSimpleSchedule(u=>u.WithIntervalInSeconds(5).RepeatForever()).Build();

            //把定时任务作业,和触发器加入调度器
            scheduler.ScheduleJob(job1, trigger1);
        }
    }
}

Call trigger timing tasks performed:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //调用调度器
            Console.WriteLine("Job Start");

            DemoScheule.Start();

            Console.ReadKey();

        }
    }
}

A job (with parameters) to achieve specific tasks

using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzTest
{
    /// <summary>
    /// 用于演示需要定时执行的任务(带参数)
    /// </summary>
    class DemoJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            string str = dataMap.GetString("id");  //调用数据

            Console.WriteLine(string.Format("Exceute Job :{0} 执行时间:{1}",str, DateTime.Now.ToString()));
        }
    }
}

Creating a trigger (parameters) concrete realization:

using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuartzTest
{
    /// <summary>
    /// 调度器
    /// </summary>
    class DemoScheule
    {
        public static void Start()
        {
            /*------Demo1 无参数 简单调用的方法 -----------*/

            //实例化调度器工厂
            ISchedulerFactory schedulefactory = new StdSchedulerFactory();

            //通过调度工厂获取一个调度器对象
            IScheduler scheduler = schedulefactory.GetScheduler();

            //启动调度器
            scheduler.Start();

            //创建一个定时任务作业
            IJobDetail job1 = JobBuilder
                .Create<DemoJob>()
                .WithIdentity("DemoJob", "groupa")
                .UsingJobData("id","1")  //装载数据
                .Build();

            //创建一个触发器
            ITrigger trigger1 = TriggerBuilder
                .Create()
                .WithIdentity("DemoTrigger","groupa")
                .StartNow()
                //.WithSimpleSchedule(u=>u.WithIntervalInSeconds(5).RepeatForever()) //设置每五秒执行一次,无限循环执行
                .WithSimpleSchedule(u=>u.WithIntervalInSeconds(3).WithRepeatCount(2)) //3秒执行一次执行两次后停止, 开始运行会执行一次
                .Build();

            //把定时任务作业,和触发器加入调度器
            scheduler.ScheduleJob(job1, trigger1);
        }
    }
}

Call flip-flops perform regular tasks, the process is the same as above.

Use configuration

上面我们进行任务调度都是通过代码来实现的,当我们要修改歹毒规则的时候,就要重新编译代码这是很不方便的,Quartz .Net 提供了通过配置文件的方式来进行操作.

首先我们在Web.Config或app.Config里面进行配置<Quartz></Quartz>节点的数据.

Quartz在Web.Config或App.Config中块描述.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <!--我们需要将Quartz的块配置声明放到startup块的最前面,否则会报错.-->
  
  <configSections>
    <!--声明Quzrtz块-->
    <section name="Quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
  </configSections>
  
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>

  <!--对Quartz块的描述-->
  <Quartz>
    <add key="quartz.scheduler.instanceName" value="ServerScheduler" />

    <add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz" />
    <add key="quartz.threadPool.threadCount" value="10" />
    <add key="quartz.threadPool.threadPriority" value="Normal" />

    <add key="quartz.plugin.xml.type" value = "Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz" />
    <add key="quartz.plugin.xml.fileNames" value = "quartz_jobs.xml" />

    <add key="quartz.jobStore.misfireThreshold" value="60000" />
    <add key="quartz.jobStore.type" value="Quartz.Simpl.RAMJobStore, Quartz" />
    
  </Quartz>
  
</configuration>

Guess you like

Origin www.cnblogs.com/HelloZyjS/p/12659890.html
Recommended