Quartz Learning--Basic Introduction to Quartz and Cron Expressions

Quartz Learning

 

1. Introduction to Quartz

  1. Quartz is an open source task schedule management system developed entirely by java

    ​The task schedule management system in other words:

    ​ When a predetermined schedule time arrives, a system responsible for executing the task

  2. Quartz uses a .jar library file that contains all of Quartz's core functionality,

    1. These functions have one main interface: the Schedule interface

      It provides simple operations such as:

      ​ Add or remove tasks from the schedule

      ​ Start/stop/pause schedule progress

  3. Types of timers:

    There are five types of Triggers in Quartz:

    • SimpleTrigger : used to trigger tasks that need to be executed only once or at a given time and repeated N times with a delay of a certain time each time

    • CronTrigger : Triggered according to the calendar, such as every Friday at 2:30 am on the 1st of every month

    • DateIntervalTrigger

    • NthIncludedDayTrigger

    • Calendar 类(org.quartz.Calendar)

  4. Storage method:

    Quartz itself supports two storage methods:

    • RAMJobStore (stored in the current memory by Gu Mingsi)

    • JDBCJobStore (to database via jdbc instance)

    Compared:

    storage type advantage shortcoming
    RAMJobStore No external database required, simple configuration and fast operation Because the scheduler information is stored in the jvm, the jvm program will be lost when it stops running and there is a limit on the number of storage due to the memory size
    JDBCJobStore can be stored in a database can control things Because it needs to connect to the database, the running speed is affected
  5. Table relationship and explanation

  

   
table name illustrate
qrtz_blob_triggers Trigger is stored as a Blob type (for Quartz users to create their own custom Trigger type with JDBC, when the JobStore doesn't know how to store the instance)
qrtz_calendars Quartz's Calendar calendar information is stored in Blob type. Quartz can configure a calendar to specify a time range
qrtz_cron_triggers Stores the Cron Trigger, including Cron expressions and timezone information.
qrtz_fired_triggers Stores state information related to the triggered Trigger and execution information of the associated Job
qrtz_job_details Stores detailed information about each configured Job
qrtz_locks Stores program non-observant lock information (if pessimistic locking is used)
qrtz_paused_trigger_graps Stores information about a paused Trigger group
qrtz_scheduler_state Store a small amount of state information about the Scheduler, and other Scheduler instances (if used in a cluster)
qrtz_simple_triggers Store simple triggers, including repeat count, interval, and number of hits
qrtz_triggers Stores information about the configured Trigger
qrzt_simprop_triggers  
  1. Core classes and relationships

    1. core class

      • QuartzSchedulerThread:

        Responsible for executing the worker thread that triggers the trigger registered with the QuartzScheduler

      • ThreadPool :

        Scheduler uses a thread as the infrastructure for task running, and tasks improve running efficiency by sharing threads in the thread pool

      • QuartzSchedulerResources :

        Contains all resources (JobStore, ThreadPool, etc.) required to wear a QuartzScheduler instance

      • JobStore :

        An interface implemented by classes that provide an org.quartz.Job and org.quartz.Trigger storage mechanism for use by org.quartz.core.QuartzScheduler. Jobs and triggers should be stored with their name and group combination as uniqueness

      • QuartzScheduler :

        The core of Quartz, it is an indirect implementation of the org.quartz.Scheduler interface, including methods for scheduling org.quartz.Jobs, registering org.quartz.JobListener instances, etc.

      • Scheduler :

        This is the main interface of the Quartz Scheduler, representing a standalone running container. The scheduler maintains a registry of JobDetails and triggers. Once registered, schedulers are responsible for executing jobs when their associated triggers fire (when their scheduled time arrives) Time )

      • Trigger:

        A basic interface with properties common to all triggers, describing the time triggering rules for job execution,

        Use TriggerBuilder to instantiate the actual trigger

      • JobDetail :

        Pass the details property for the given job instance.

        JobDetails will be created/defined using JobBuilder

      • Job :

        Implementing interface for the class representing the "job" to execute.

        There is only one way:

        void execute(JobExecutionContext context);

        (JobExecutionContext provides various information of scheduling context, and runtime data is stored in jobDataMap)

        Job has a sub-interface StatefulJob, which means there is no state task

        Stateful tasks cannot be concurrent, the previous task has not been executed, and the subsequent tasks are always in the blocking waiting state

    2. A job can be bound by multiple triggers, but a trigger can only be bound to one job!

  2. quartz.properties Quartz can change the configuration

    //Scheduling identifiers Each instance in the cluster must use the same name (distinguishes a specific scheduler instance)
    org.quartz.scheduler.instanceName:DefaultQuartzScheduler
    //ID is set to automatically get each one must be different (unique among all scheduler instances)
    org.quartz.scheduler.instanceId :AUTO
    //The data is saved in persistence mode
    org.quartz.jobStore.class :org.quartz.impl.jdbcjobstore.JobStoreTX
    // prefix of the table
    org.quartz.jobStore.tablePrefix : QRTZ_
    //Setting to TRUE will not cause class version problems when serializing non-string classes to BLOBs
    //org.quartz.jobStore.useProperties : true
    //Join the cluster true is the cluster false is not the cluster
    org.quartz.jobStore.isClustered : false
    //Check time interval for scheduling instance failure
    org.quartz.jobStore.clusterCheckinInterval:20000
    //Maximum allowable job extension time
    org.quartz.jobStore.misfireThreshold :60000
    //Class name implemented by ThreadPool
    org.quartz.threadPool.class:org.quartz.simpl.SimpleThreadPool
    // number of threads
    org.quartz.threadPool.threadCount : 10
    // thread priority
    org.quartz.threadPool.threadPriority: 5 (the maximum value of the threadPriority attribute is the constant java.lang.Thread.MAX_PRIORITY, which is equal to 10. The minimum value is the constant java.lang.Thread.MIN_PRIORITY, which is 1)
    //Self-created parent thread
    //org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true
    //database alias
    org.quartz.jobStore.dataSource : qzDS
    //set the data source
    org.quartz.dataSource.qzDS.driver:com.mysql.jdbc.Driver
    org.quartz.dataSource.qzDS.URL:jdbc:mysql://localhost:3306/quartz
    org.quartz.dataSource.qzDS.user:root
    org.quartz.dataSource.qzDS.password:123456
    org.quartz.dataSource.qzDS.maxConnection:10
    

      

  3. JDBC insert table order

    The main JDBC operation class, the execution sql order: 
    ​Basic
    order: record job content   Insert trigger list   corresponding type trigger rule warehousing   triggered job information and trigger information Simple_trigger: Insert order qrtz_job_details ---> qrtz_triggers ---> qrtz_simple_triggers qrtz_fired_triggers ​Cron_Trigger : Insertion order qrtz_job_details ---> qrtz_triggers ---> qrtz_cron_triggers qrtz_fired_triggers











2. Cron expressions

  1. Why use cron expressions

    We mentioned earlier that there are five triggers that we use

    Among them, SimpleTrigger and CronTrigger are commonly used

    • SimpleTrigger is a schedule that does work iteratively at a fully specified time

  • CronTrigger has plenty of schedules that can be scheduled according to the calendar and it includes the initial startup time in the Simple plan

    E.g:

    • Every Friday at noon

    • 10:30am every weekday

    • Wed and Fri 9:00-10:00 every five minutes

  1. Cron Expressions

    Cron expression is not only used in Quartz, in fact, it is also used in Linux timing tasks as a special expression, and Spring's @Scheduled annotation in java is also used

    Cron expressions are in string form

    Cron is essentially composed of seven sub-expressions , describing the schedule of individual details and these sub-expressions are separated by spaces

    Subexpression:

    Location significance valid value Available special characters
    1 Seconds 0-59 , - * /
    2 Minutes 0-59 , - * /
    3 Hours 0 - 23 , - * /
    4 Day-of-Month 1 - 31 (note some special months) , - * / ? L W
    5 Month 0 - 11 or the string "JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV DEC" , - * /
    6 Day-of-Week (Weekly) 1 - 7 or the string "SUN, MON, TUE, WED, THU, FRI, SAT" means * Note: 1==SUN , - * / ? L #
    7 Year (year optional field) empty or 1970-2099 , - * /
    1. Special characters

      Obviously, it is not possible to write an expression that is executed repeatedly through subexpressions

      And special characters are to solve the current problem

    Special characters :

    symbol Express for example
    / Every Used in conjunction with the current sub-expression to occupy a sub-expression position Example: "3/15" is placed on the second sub-expression position, which means that the execution starts at the third minute and executes every 15 minutes
    ? one day 只存在与 Day-of-Month 和 Day-of-Week 中使用,来解决 这两个表达式的冲突问题 在其中一个子表达式有值的情况下 ?写在另一个表达式上表示匹配任意值,这样我们就不会再用* 去来表示匹配任意值了 例: 每月15号的早上4点 : "0 0 4 15 * ?" 每周五晚上11点: "0 0 23 ? * FRI"
    L 每月 或每周 的最后一天 只存在与 Day-of-Month 和 Day-of-Week 中使用, Day-of-Month 子表达式中,“L”表示一个月的最后一天 Day-of-Week 子表达式中,“L”表示一个星期的最后一天,也就是SAT 例: “0 15 10 ? * 6L” 表示 每月最后一个星期五10:15分运行。 "0 15 10 2L * ?" 表示 每月倒数第二天10:15分运行。
    W 最近工作日 只存在与 Day-of-Month 最近的工作日: 例: "0 15 10 15W * ?" 每个月距离15日最近的工作日 如 15日是周六则执行时间是14日 若15日是周日 则执行时间是16 如15号是工作日就15执行 就近匹配不会跨出当前月
    # 第几个星期几 只存在与 Day-of-Week 中 每月第n个工作日 例:“0 15 10 ? * 6#3” 表示每个月第三个星期五 “0 15 10 ? * 4#2” 表示每个月第二个星期三
    , 多个 例: "0 0 0,13,18,21 * * ?": 每天的0点、13点、18点、21点都执行一次:
    - 区间 例: "0 0-5 14 * * ?" : 在每天下午2点到下午2:05期间的每1分钟触发
    * 补位符 补位 但是 注意: Day-of-Month 和 Day-of-Week 肯定有一个为 ? 也不能两个 ?

    综合例子:

    "0 30 0-4 ? 3,7 5#2 2018":

    ​ 每30分钟执行一次

    ​ 凌晨的0-4 点

    ​ 每个月

    ​ 3 月和 7月

    ​ 第二个周四

    ​ 2018年

    ​ : 2018年 的三月和7月的第二个周四的凌晨0-4点 开始每30分钟执行一次

    "0 30 4 10LW * ?":

    ​ 第四位是 Day-of-Month L在此表示 每个月最后

    ​ 10L表示每月的倒数第十天 (不一定是21号 月份不同倒数的第几天也就不同 )​ W表示 附近的工作日

    ​ 所以表示每个月离倒数第十天最近的工作日的凌晨4点30分执行一次

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326462615&siteId=291194637