Quartz.Net 使用

Quartz.NET  是一套很好的任务调度框架。

下面介绍如何使用:

在项目Nuget包管理器中搜索:quartz

Quartz.Net 使用_第1张图片

安装后会添加如下dll:


  "Common.Logging" version="3.0.0" targetFramework="net452" />
  "Common.Logging.Core" version="3.0.0" targetFramework="net452" />
  "Quartz" version="2.3.3" targetFramework="net452" />

简单场景

先定义一个Job,需要实现IJob接口:

public class HelloJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            Console.WriteLine("Hello " + DateTime.Now.ToString());
        }
    }

启动Job:

static void Main(string[] args)
        {
            ISchedulerFactory schedFact = new StdSchedulerFactory();
            IScheduler sched = schedFact.GetScheduler();
            sched.Start();
            IJobDetail job = JobBuilder.Create()
                .WithIdentity("myJob", "group1")
                .Build();
            ITrigger trigger = TriggerBuilder.Create()
              .WithIdentity("myTrigger", "group1")
              .StartNow()
              .WithSimpleSchedule(x => x
                  .WithIntervalInSeconds(3)
                  .RepeatForever())
              .Build();
            sched.ScheduleJob(job, trigger);
        }

Quartz.Net 使用_第2张图片

这里有几个概念:

  • IScheduler - the main API for interacting with the scheduler.
  • IJob - an interface to be implemented by components that you wish to have executed by the scheduler.
  • IJobDetail - used to define instances of Jobs.
  • ITrigger - a component that defines the schedule upon which a given Job will be executed.
  • JobBuilder - used to define/build JobDetail instances, which define instances of Jobs.
  • TriggerBuilder - used to define/build Trigger instances.

TriggerBuilder的触发类型有以下四种:

  • WithCalendarIntervalSchedule
  • WithCronSchedule
  • WithDailyTimeIntervalSchedule
  • WithSimpleSchedule

每个Job和Trigger都有自己的身份标识Identity。

使用JobDataMap

static void Main(string[] args)
        {
            ISchedulerFactory schedFact = new StdSchedulerFactory();
            IScheduler sched = schedFact.GetScheduler();
            sched.Start();
            
            IJobDetail job = JobBuilder.Create()
    .WithIdentity("myJob", "group1") 
    .UsingJobData("jobSays", "Hello World!")
    .UsingJobData("myFloatValue", 3.141f)
    .Build();
            ITrigger trigger = TriggerBuilder.Create()
              .WithIdentity("myTrigger", "group1")
              .StartNow()
              .WithSimpleSchedule(x => x
                  .WithIntervalInSeconds(3)
                  .RepeatForever())
              .Build();
            sched.ScheduleJob(job, trigger);
        }
public class DumbJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            JobKey key = context.JobDetail.Key;
            JobDataMap dataMap = context.JobDetail.JobDataMap;
            string jobSays = dataMap.GetString("jobSays");
            float myFloatValue = dataMap.GetFloat("myFloatValue");
            Console.Error.WriteLine("Instance " + key + " of DumbJob says: " + jobSays + ", and val is: " + myFloatValue);
        }
    }

Quartz.Net 使用_第3张图片

可以看到,通过JobDataMap可以给Job传递参数。

JobDataMap也可以从上下文获取:

JobKey key = context.JobDetail.Key;
            //JobDataMap dataMap = context.JobDetail.JobDataMap;
            JobDataMap dataMap = context.MergedJobDataMap; 

还可以设置为属性注入:

public class DumbJob : IJob
    {
        public string JobSays { private get; set; }
        public float MyFloatValue { private get; set; }

        public void Execute(IJobExecutionContext context)
        {
            JobKey key = context.JobDetail.Key;
            JobDataMap dataMap = context.MergedJobDataMap;
            Console.Error.WriteLine("Instance " + key + " of DumbJob says: " + JobSays + ", and val is: " + MyFloatValue);
        }
    }

并发限制

修改HelloJob如下:

public class HelloJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            Console.WriteLine("Hello " + DateTime.Now.ToString());
            Thread.Sleep(5 * 1000);
        }
    }

Quartz.Net 使用_第4张图片

可以看到仍然是每3秒跑一次,说明有多个实例在运行。

加上并发限制:

[DisallowConcurrentExecution]
    public class HelloJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            Console.WriteLine("Hello " + DateTime.Now.ToString());
            Thread.Sleep(5 * 1000);
        }
    }

Quartz.Net 使用_第5张图片

可以看到是每隔5秒才运行。

关于Job还有几个概念:

  • Durability - if a job is non-durable, it is automatically deleted from the scheduler once there are no longer any active triggers associated with it. In other words, non-durable jobs have a life span bounded by the existence of its triggers.
  • RequestsRecovery - if a job "requests recovery", and it is executing during the time of a 'hard shutdown' of the scheduler (i.e. the process it is running within crashes, or the machine is shut off), then it is re-executed when the scheduler is started again. In this case, the JobExecutionContext.Recovering property will return true.
  • PersistJobDataAfterExecution is an attribute that can be added to the Job class that tells Quartz to update the stored copy of the JobDetail's JobDataMap after the Execute() method completes successfully (without throwing an exception), such that the next execution of the same job (JobDetail) receives the updated values rather than the originally stored values. 

Trigger 相关:

  • Priority

  • Misfire

  • Calendars

 

SimpleTrigger:

Build a trigger for a specific moment in time, with no repeats:

// trigger builder creates simple trigger by default, actually an ITrigger is returned
ISimpleTrigger trigger = (ISimpleTrigger) TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartAt(myStartTime) // some Date .ForJob("job1", "group1") // identify job with name, group strings .Build(); 

Build a trigger for a specific moment in time, then repeating every ten seconds ten times:

trigger = TriggerBuilder.Create() .WithIdentity("trigger3", "group1") .StartAt(myTimeToStartFiring) // if a start time is not given (if this line were omitted), "now" is implied .WithSimpleSchedule(x => x .WithIntervalInSeconds(10) .WithRepeatCount(10)) // note that 10 repeats will give a total of 11 firings .ForJob(myJob) // identify job with handle to its JobDetail itself .Build(); 

Build a trigger that will fire once, five minutes in the future:

trigger = (ISimpleTrigger) TriggerBuilder.Create() .WithIdentity("trigger5", "group1") .StartAt(DateBuilder.FutureDate(5, IntervalUnit.Minute)) // use DateBuilder to create a date in the future .ForJob(myJobKey) // identify job with its JobKey .Build(); 

Build a trigger that will fire now, then repeat every five minutes, until the hour 22:00:

trigger = TriggerBuilder.Create() .WithIdentity("trigger7", "group1") .WithSimpleSchedule(x => x .WithIntervalInMinutes(5) .RepeatForever()) .EndAt(DateBuilder.DateOf(22, 0, 0)) .Build(); 

Build a trigger that will fire at the top of the next hour, then repeat every 2 hours, forever:

trigger = TriggerBuilder.Create() .WithIdentity("trigger8") // because group is not specified, "trigger8" will be in the default group .StartAt(DateBuilder.EvenHourDate(null)) // get the next even-hour (minutes and seconds zero ("00:00")) .WithSimpleSchedule(x => x .WithIntervalInHours(2) .RepeatForever()) // note that in this example, 'forJob(..)' is not called // - which is valid if the trigger is passed to the scheduler along with the job .Build(); scheduler.scheduleJob(trigger, job);

CronTrigger

http://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/crontrigger.html

Expressions:

  • 1. Seconds
  • 2. Minutes
  • 3. Hours
  • 4. Day-of-Month
  • 5. Month
  • 6. Day-of-Week
  • 7. Year (optional field)

"0 0 12 ? * WED" - which means "every Wednesday at 12:00 pm".

可以把上面的“WED"替换成: "MON-FRI", "MON, WED, FRI", or even "MON-WED,SAT".

上面表达式的“*”表示“每月”

如果Minutes的数值是 '0/15' ,表示从0开始每15分钟执行

如果Minutes的数值是 '3/20' ,表示从3开始每20分钟执行,也就是‘3/23/43’

‘?’只能用在day-of-month 和 day-of-week,表示没有特定的值

 'L' 只能用在 day-of-month 和 day-of-week fields. 如 "L" 在 day-of-month 表示 "当月最后一天" . 单独用在 day-of-week 表示 "7" or "SAT". "6L" or "FRIL" 表示"当月最后一个星期五".

'W' :"15W" 在 day-of-month 表示: "离15号最近的周一到周五".

 '#' :"6#3" 或 "FRI#3" 在 day-of-week 表示 "当月第三个星期五".

Seconds范围:0-59

Minutes范围:0-59

Hours范围:0-23

Day-of-Month范围:0-31(需要注意月份没有31天的)

Month范围:0-11 或者使用JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV and DEC.

Day-of-Week范围:1-7 (1 = Sunday) 或SUN, MON, TUE, WED, THU, FRI and SAT.

CronTrigger Example 1 - 每5分钟执行

"0 0/5 * * * ?"

CronTrigger Example 2 -每5分钟的第10秒执行

"10 0/5 * * * ?"

CronTrigger Example 3 - 每个星期三和星期五的10:30, 11:30, 12:30, 13:30执行

"0 30 10-13 ? * WED,FRI"

CronTrigger Example 4 - 每月第5天和第20天从8点到9点每30分钟执行. 注意 10:00 不会执行, 只有 8:00, 8:30, 9:00 ,9:30

"0 0/30 8-9 5,20 * ?"

Build a trigger that will fire every other minute, between 8am and 5pm, every day:

trigger = TriggerBuilder.Create() .WithIdentity("trigger3", "group1") .WithCronSchedule("0 0/2 8-17 * * ?") .ForJob("myJob", "group1") .Build(); 

Build a trigger that will fire daily at 10:42 am:

// we use CronScheduleBuilder's static helper methods here
trigger = TriggerBuilder.Create() .WithIdentity("trigger3", "group1") .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(10, 42)) .ForJob(myJobKey) .Build(); 

or -

trigger = TriggerBuilder.Create() .WithIdentity("trigger3", "group1") .WithCronSchedule("0 42 10 * * ?") .ForJob("myJob", "group1") .Build(); 

Build a trigger that will fire on Wednesdays at 10:42 am, in a TimeZone other than the system's default:

trigger = TriggerBuilder.Create() .WithIdentity("trigger3", "group1") .WithSchedule(CronScheduleBuilder .WeeklyOnDayAndHourAndMinute(DayOfWeek.Wednesday, 10, 42) .InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Central America Standard Time"))) .ForJob(myJobKey) .Build(); 

or -

trigger = TriggerBuilder.Create() .WithIdentity("trigger3", "group1") .WithCronSchedule("0 42 10 ? * WED", x => x .InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Central America Standard Time"))) .ForJob(myJobKey) .Build();

TriggerListeners and JobListeners

Adding a JobListener that is interested in a particular job:

scheduler.ListenerManager.AddJobListener(myJobListener, KeyMatcher<JobKey>.KeyEquals(new JobKey("myJobName", "myJobGroup"))); 

Adding a JobListener that is interested in all jobs of a particular group:

scheduler.ListenerManager.AddJobListener(myJobListener, GroupMatcher<JobKey>.GroupEquals("myJobGroup")); 

Adding a JobListener that is interested in all jobs of two particular groups:

scheduler.ListenerManager.AddJobListener(myJobListener, OrMatcher<JobKey>.Or(GroupMatcher<JobKey>.GroupEquals("myJobGroup"), GroupMatcher<JobKey>.GroupEquals("yourGroup"))); 

Adding a JobListener that is interested in all jobs:

scheduler.ListenerManager.AddJobListener(myJobListener, GroupMatcher<JobKey>.AnyGroup());

SchedulerListeners

Adding a SchedulerListener:

scheduler.ListenerManager.AddSchedulerListener(mySchedListener); 

Removing a SchedulerListener:

scheduler.ListenerManager.RemoveSchedulerListener(mySchedListener);

JobStores

Quartz 默认是存在内存的,也就是如下配置:

quartz.jobStore.type = Quartz.Simpl.RAMJobStore, Quartz

还可以存在数据库中,可以从https://github.com/quartznet/quartznet database目录中找到建库脚本

Quartz.Net 使用_第6张图片

可以看到创建了11张表,都是以qrtz_ 开头的,这个可以在配置里更改

quartz.jobStore.tablePrefix = QRTZ_

配置使用数据库:

quartz.jobStore.type = Quartz.Impl.AdoJobStore.JobStoreTX, Quartz

配置数据库代理:

quartz.jobStore.driverDelegateType = Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz

这里类型有:

MySQLDelegate 
SqlServerDelegate 
OracleDelegate 
SQLiteDelegate

配置使用哪个数据库:

quartz.jobStore.dataSource = myDS

配置连接属性:

 quartz.dataSource.myDS.connectionString = Server=localhost;Database=quartz;Uid=quartznet;Pwd=quartznet
 quartz.dataSource.myDS.provider = MySql-695

配置所有的JobDataMap 都是string类型:

quartz.jobStore.useProperties = true

配置集群:

quartz.jobStore.clustered=true

配置线程池:

quartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartz
quartz.threadPool.threadCount = 10
quartz.threadPool.threadPriority = Normal

配置读取配置:

quartz.plugin.jobInitializer.type=Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin
quartz.plugin.jobInitializer.fileNames=~/quartz_jobs.xml
quartz.plugin.jobInitializer.failOnFileNotFound=true

配置实例名:

quartz.scheduler.instanceName = QuartzTest

如果不配置的话默认是QuartzScheduler,如下图所示:

只保留简单的HelloJob,运行,查看数据库,可以看到这几张表里有数据:

Quartz.Net 使用_第7张图片


更改重复次数为10次,先运行3次:

Quartz.Net 使用_第8张图片

可以看到最后字段是3次,重新运行程序:

ISchedulerFactory schedFact = new StdSchedulerFactory();
            IScheduler sched = schedFact.GetScheduler();
            sched.Start();

注意这里不要再加任务了。

Quartz.Net 使用_第9张图片

可以看到剩余次数Repeat_Count是7次了,当这7次运行完后这几个表就清空了。

使用配置文件配置任务

在项目根目录下创建quartz_jobs.xml并设置始终复制

"1.0" encoding="utf-8" ?>
"http://quartznet.sourceforge.net/JobSchedulingData"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 version="2.0">

  
    false
  

  

    
      HelloJob
      jobGroup1
      jobDesciption1
      Jobs.SimpleJob, Jobs
      true
      true
    

    
      
        simpleName
        simpleGroup
        SimpleTriggerDescription
        HelloJob
        jobGroup1
        2016-07-01T17:40:00.0Z
        2020-05-04T18:13:51.0Z
        SmartPolicy
        100
        3000
      
    
    
    
      TestJob
      Test
      TestJob测试
      Jobs.TestJob,Jobs
      true
      false
    
    
      
        TestJobTrigger
        Test
        TestJob
        Test
        2016-07-04T00:00:00+08:00
        0/3 * * * * ?
      
    
    

  

View Code

运行程序,发现数据库里有了记录,可是却没有运行任务。关了再次运行才开始跑任务,而如果这里的配置是true的话,再次运行也只是写库,不运行任务:


    true
  

 这里关键就在节点,把两个时间节点注释后可以正常运行:

"1.0" encoding="utf-8" ?>
"http://quartznet.sourceforge.net/JobSchedulingData"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 version="2.0">

  
    true
  

  

    
      HelloJob
      jobGroup1
      jobDesciption1
      Jobs.SimpleJob, Jobs
      true
      true
    

    
      
        simpleName
        simpleGroup
        SimpleTriggerDescription
        HelloJob
        jobGroup1
        
        SmartPolicy
        100
        3000
      
    

    
      TestJob
      Test
      TestJob测试
      Jobs.TestJob,Jobs
      true
      false
    
    
      
        TestJobTrigger
        Test
        TestJob
        Test
        
        0/3 * * * * ?
      
    


  

View Code

下面是其他园友总结的:

Quartz.NET 入门

Quartz.NET 2.0 学习笔记(3) :通过配置文件实现任务调度

job 任务,这个节点是用来定义每个具体的任务的,多个任务请创建多个job节点即可

  • name(必填) 任务名称,同一个group中多个job的name不能相同,若未设置group则所有未设置group的job为同一个分组,如:sampleJob
  • group(选填) 任务所属分组,用于标识任务所属分组,如:sampleGroup
  • description(选填) 任务描述,用于描述任务具体内容,如:Sample job for Quartz Server
  • job-type(必填) 任务类型,任务的具体类型及所属程序集,格式:实现了IJob接口的包含完整命名空间的类名,程序集名称,如:Quartz.Server.SampleJob, Quartz.Server
  • durable(选填) 具体作用不知,官方示例中默认为true,如:true
  • recover(选填) 具体作用不知,官方示例中默认为false,如:false

trigger 任务触发器,用于定义使用何种方式出发任务(job),同一个job可以定义多个trigger ,多个trigger 各自独立的执行调度,每个trigger 中必须且只能定义一种触发器类型(calendar-interval、simple、cron)

calendar-interval 一种触发器类型,使用较少,此处略过

simple 简单任务的触发器,可以调度用于重复执行的任务

  • name(必填) 触发器名称,同一个分组中的名称必须不同
  • group(选填) 触发器组
  • description(选填) 触发器描述
  • job-name(必填) 要调度的任务名称,该job-name必须和对应job节点中的name完全相同
  • job-group(选填) 调度任务(job)所属分组,该值必须和job中的group完全相同
  • start-time(选填) 任务开始执行时间utc时间,北京时间需要+08:00,如:2012-04-01T08:00:00+08:00表示北京时间2012年4月1日上午8:00开始执行,注意服务启动或重启时都会检测此属性,若没有设置此属性或者start-time设置的时间比当前时间较早,则服务启动后会立即执行一次调度,若设置的时间比当前时间晚,服务会等到设置时间相同后才会第一次执行任务,一般若无特殊需要请不要设置此属性
  • repeat-count(必填)  任务执行次数,如:-1表示无限次执行,10表示执行10次
  • repeat-interval(必填) 任务触发间隔(毫秒),如:10000 每10秒执行一次

cron复杂任务触发器--使用cron表达式定制任务调度(强烈推荐)

  • name(必填) 触发器名称,同一个分组中的名称必须不同
  • group(选填) 触发器组
  • description(选填) 触发器描述
  • job-name(必填) 要调度的任务名称,该job-name必须和对应job节点中的name完全相同
  • job-group(选填) 调度任务(job)所属分组,该值必须和job中的group完全相同
  • start-time(选填) 任务开始执行时间utc时间,北京时间需要+08:00,如:2012-04-01T08:00:00+08:00表示北京时间2012年4月1日上午8:00开始执行,注意服务启动或重启时都会检测此属性,若没有设置此属性,服务会根据cron-expression的设置执行任务调度;若start-time设置的时间比当前时间较早,则服务启动后会忽略掉cron-expression设置,立即执行一次调度,之后再根据cron-expression执行任务调度;若设置的时间比当前时间晚,则服务会在到达设置时间相同后才会应用cron-expression,根据规则执行任务调度,一般若无特殊需要请不要设置此属性
  • cron-expression(必填) cron表达式,如:0/10 * * * * ?每10秒执行一次

TriggerListeners and JobListeners

可以使用监听器来监视任务和触发器的执行状态:

public class MyJobListener : IJobListener
    {
        public string Name
        {
            get
            {
                return "myJobListener";
            }
        }

        public void JobExecutionVetoed(IJobExecutionContext context)
        {
            
        }

        public void JobToBeExecuted(IJobExecutionContext context)
        {
            Console.WriteLine("Job{0}开始执行。", context.JobDetail.Key);
        }

        public void JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException)
        {
            if(jobException==null)
            {
                Console.WriteLine("Job{0}执行完成。", context.JobDetail.Key);
            }
            else
            {
                Console.WriteLine("Job{0}执行失败:{1}", context.JobDetail.Key, jobException.Message);
            }
        }
    }

 

IScheduler sched = StdSchedulerFactory.GetDefaultScheduler();
                MyJobListener myJobListener = new MyJobListener();
                sched.ListenerManager.AddJobListener(myJobListener, GroupMatcher.GroupEquals("Test"));
                sched.Start();

Quartz.Net 使用_第10张图片

The ITriggerListener Interface

public interface ITriggerListener
{
     string Name { get; } void TriggerFired(ITrigger trigger, IJobExecutionContext context); bool VetoJobExecution(ITrigger trigger, IJobExecutionContext context); void TriggerMisfired(ITrigger trigger); void TriggerComplete(ITrigger trigger, IJobExecutionContext context, int triggerInstructionCode); } 

Job-related events include: a notification that the job is about to be executed, and a notification when the job has completed execution.

The IJobListener Interface

public interface IJobListener
{
    string Name { get; } void JobToBeExecuted(IJobExecutionContext context); void JobExecutionVetoed(IJobExecutionContext context); void JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException); } 

Adding a JobListener that is interested in a particular job:

scheduler.ListenerManager.AddJobListener(myJobListener, KeyMatcher<JobKey>.KeyEquals(new JobKey("myJobName", "myJobGroup"))); 

Adding a JobListener that is interested in all jobs of a particular group:

scheduler.ListenerManager.AddJobListener(myJobListener, GroupMatcher<JobKey>.GroupEquals("myJobGroup")); 

Adding a JobListener that is interested in all jobs of two particular groups:

scheduler.ListenerManager.AddJobListener(myJobListener, OrMatcher<JobKey>.Or(GroupMatcher<JobKey>.GroupEquals("myJobGroup"), GroupMatcher<JobKey>.GroupEquals("yourGroup"))); 

Adding a JobListener that is interested in all jobs:

scheduler.ListenerManager.AddJobListener(myJobListener, GroupMatcher<JobKey>.AnyGroup());

Quartz 定时器动态创建任务和修改执行时间修改后出现立即执行情况


https://blog.csdn.net/liufei198613/article/details/77746892

转载于:https://www.cnblogs.com/uptothesky/p/5633421.html

你可能感兴趣的:(Quartz.Net 使用)