QUARTZ系列之一-基础概念(Scheduler/Job/JobDetail/Trigger)

时间:2023-12-29 13:34:20

摘抄自quartz官方文档:

The key interfaces of the Quartz API are:

  • Scheduler - the main API for interacting with the scheduler.  (quartz提供的用来和调度器交互的API)
  • Job - an interface to be implemented by components that you wish to have executed by the scheduler.(你希望被调度的任务体)
  • JobDetail - used to define instances of Jobs.  (用来定义任务实例)
  • Trigger - a component that defines the schedule upon which a given Job will be executed. (定义了Job运行的调度时间表(即schedule,注意与scheduler的区别))
  • JobBuilder - used to define/build JobDetail instances, which define instances of Jobs.(job构建器,quartz特有的DSL)
  • TriggerBuilder - used to define/build Trigger instances.(trigger构建器,quartz特有的DSL)

Quartz provides “builder” classes that define a Domain Specific Language (or DSL, also sometimes referred to as a “fluent interface”).

quartz定义了一套DSL,其实也就是一套bulider模式。值得注意的是,JobBuilder的doc中有这样一句:

The builder will always try to keep itself in a valid state, with reasonable defaults set for calling build() at any point. 

For instance if you do not invoke <i>withIdentity(..)</i> a job name will be generated for you.

builder会努力使自己处于有效的状态。

Scheduler:

scheduler:调度器,没啥好讲的。various “ScheduleBuilder” classes build出各种不同的scheduler。

Trigger:

1.1 SimpleTrigger:

1.2 CronTrigger:

1.2.1.特点:recurs based on calendar-like notions,such as "every Friday at noon","every weekday and 9:30 am",even "every 5 minutes between 9:00 am and 10:00 am on every Monday, Wednesday and Friday during January".

1.2.2 CRON表达式:自己百度

1.2.3 使用:

using TriggerBuilder (for the trigger’s main properties) and CronScheduleBuilder (for the CronTrigger-specific properties).

To use these builders in a DSL-style, use static imports:

import static org.quartz.TriggerBuilder.*;
import static org.quartz.CronScheduleBuilder.*;
import static org.quartz.DateBuilder.*:

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

  trigger = newTrigger()
.withIdentity("trigger3", "group1")
.withSchedule(cronSchedule("0 0/2 8-17 * * ?"))
.forJob("myJob", "group1")
.build();

1.2.4 Misfire说明:

Misfire Instruction Constants of CronTrigger:

MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY                                   // java doc中未见此字段,但是官方文档有此字段
MISFIRE_INSTRUCTION_DO_NOTHING = 2 // 1. 更新next-fire-time;2.本次不执行
MISFIRE_INSTRUCTION_FIRE_NOW = 1 // to be fired now

Note:1.也有Trigger.MISFIRE_INSTRUCTION_SMART_POLICY字段,当作MISFIRE_INSTRUCITON_FIRE_NOW 处理。

2.行为的具体细节参考CronTrigger.updateAfterMisfire()方法

3.使用方式:放到schedule中定义即可:

cronSchedule("0 0/2 8-17 * * ?")
..withMisfireHandlingInstructionFireAndProceed()