quartz timed task scheduling

Author: Shine

Version: 9.0.2

1, Introduction

1.1 INTRODUCTION

Quartz : http://www.quartz-scheduler.org/

It's a Timed task scheduling framework . For example, you encounter such problems:

  • Want to check whether the order is paid after 30 minutes, and cancel the order if it is not paid
  • I want to make automatic repayment by credit card on the 29th of each month
  • ...
  • Want to do something (task) at a certain time.

Quartz is to schedule scheduled tasks. Set the trigger time rules and corresponding tasks (jobs).

2, Quartz use

2.1 import dependency

<dependencies>
    <!--Quartz task scheduling -->
    <dependency>
        <groupId>org.quartz-scheduler</groupId>
        <artifactId>quartz</artifactId>
        <version>2.3.2</version>
    </dependency>
</dependencies>

2.2 defining a Job

/**
 * The specific implementation of a work class, that is, "something" that needs to be executed regularly
 * */
public class MyJob implements Job {
    //implement
    public void execute(JobExecutionContext context) throws JobExecutionException {
         //Create job details
        JobDetail jobDetail=context.getJobDetail();
        //Gets the name of the job
        String jobName = jobDetail.getKey().getName();//Task name
        String jobGroup = jobDetail.getKey().getGroup();//Task group
        System.out.println("job Execution, job: "+jobName+" group:"+jobGroup);
        System.out.println(new Date());
    }
}

2.3 API testing

package com.qf;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.GregorianCalendar;

public class TestQuartz {

    public static void main(String[] args) throws Exception{
        //Create scheduler, scheduler
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        //Define a Trigger, Trigger condition class
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "group1") //Define name/group
                .startNow()//Set the start time. Once you join the scheduler, it will take effect immediately and start timing
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(2) //Every 2 seconds
                        /// / execution time (forever(), until the end of forever())
                        .withRepeatCount(3))//Set execution times
                //Set the end time (Note: the month starts from 0 by default)
                .endAt(new GregorianCalendar(2020,5,27,17,30,10).getTime())
                .build();
        //Define a JobDetail
        JobDetail job = JobBuilder.newJob(MyJob.class)
                .withIdentity("job1","group1") //Define name/group
                .build();
        //Add tasks and triggers to the scheduler
        scheduler.scheduleJob(job, trigger);
        //Start task scheduling
        scheduler.start();
    }
}

2.4 default configuration

# Name: quartz Properties, which is placed under the classpath. If there is no such configuration, it will be started according to the default configuration
# Specify the scheduler name, not the implementation class
org.quartz.scheduler.instanceName = DefaultQuartzScheduler
# Specifies the thread pool implementation class
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
# Number of threads in thread pool
org.quartz.threadPool.threadCount = 10 
# Priority, default 5
org.quartz.threadPool.threadPriority = 5
# Non persistent job
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore

2.5 core class description

Scheduler: scheduler. All scheduling is controlled by it, which is Quartz's brain, and all tasks are managed by it

Job: task, something you want to execute regularly (define business logic)

JobDetail: further packaging based on Job. Associate a Job and specify more detailed properties for the Job, such as ID

Trigger: trigger. It can be assigned to a task and the trigger mechanism of the task.

3, Trigger

3.1 SimpleTrigger

A task that is executed at a certain time interval (in milliseconds).

  • Specify start and end times (time periods)
  • Specify time interval and execution times

Example:

SimpleTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "group1")
                .startNow()
            	.withSchedule(SimpleScheduleBuilder.simpleSchedule()
                          .withIntervalInSeconds(1) //Once per second
                          .repeatForever())// Unlimited execution times
                .endAt(new GregorianCalendar(2020, 4, 7, 2, 24, 0).getTime())
                .build();
SimpleTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "group1")
                .startNow()
            	.withSchedule(SimpleScheduleBuilder.simpleSchedule()
                          .withIntervalInMinutes(3) // Every 3 minutes
                          .withRepeatCount(3)) // No more than 3 times
                .endAt(new GregorianCalendar(2020, 4, 7, 2, 24, 0).getTime()) 
                .build();

3.2 CronTrigger [key]

Suitable for more complex tasks, it supports the syntax of Linux Cron type (and more powerful).

  • Specify Cron expression

Example:

// Every day from 10:00 to 12:00, every 2 seconds
CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger2", "group2")
                .withSchedule(CronScheduleBuilder.cronSchedule("*/2 * 10-12 * * ?"))
                .build(); 
3.2.1 composition of cron expression

Expression composition: "second minute hour day month week [year]", where "year" is optional and generally not specified.

  • For example: "10 20 18 3 5?" On behalf of "May 3, 18:20:10, the day of the week is uncertain"
position Time domain Allowable value Special value
1 second 0-59 , - * /
2 minute 0-59 , - * /
3 hour 0-23 , - * /
4 date 1-31 , - * ? / L W
5 month 1-12 , - * /
6 week 1-7 , - * ? / L #
7 Year (optional) , - * /
3.2.2 Cron expression symbols

The meanings of special symbols that can be used in expressions are as follows

Symbol semantics
Asterisk (*) It can be used in all fields to represent each time in the corresponding time domain. For example, in the minute field, it means "every minute"
Question mark (?) This character is only used in the date and week fields and is usually specified as "uncertain value"
Minus sign (-) Express a range. If "10-12" is used in the hour field, it means from 10 to 12 points, that is, 10,11,12
Comma (,) Express a list value. If "MON,WED,FRI" is used in the week field, it means Monday, Wednesday and Friday
Slash (/) x/y represents an equal step sequence, where x is the starting value and y is the incremental step value. If 0 / 15 is used in the minute field, it means 0, 15, 30 and 45 seconds, while 5 / 15 is in the minute field 5,20,35,50
Well number (#) This character is only used in the week field, "4#2" represents the second week 3 and "5#4" represents the fourth Thursday
L This character is only used in the date and week fields and represents the meaning of "Last", but it has different meanings in the two fields.
If L is used in the week field, it means Saturday, which is equivalent to 7
If l appears in the week field and is preceded by a value x, it means "X of the last week of the month". For example, 6L means the last Friday of the month
L in the date field, it indicates the last day of the month, such as the 31st of January and the 28th of February in a non leap year
W This character can only appear in the date field. It is a modification of the leading date and represents the working day closest to the date
For example, 15W represents the nearest working day from the 15th of the month. If the 15th of the month is Saturday, it matches Friday on the 14th; If the 15th is Sunday, match the 16th Monday; If the 15th It's Tuesday, so the result is Tuesday the 15th; However, it must be noted that the associated matching date cannot span months
LW combination LW can be combined in the date field, which means the last working day of the current month
3.2.3 Cron expression example

Demonstration example

Expression explain
0 0 12 * * ? It runs at 12 o'clock every day
0 15 10 * * ? Run at 10:15 every day
0 15 10 * * ? 2008 Run at 10:15 every day in 2008
0 * 14 * * ? It runs every minute between 14:00 and 15:00 every day, starting at 14:00 and ending at 14:59.
0 0/5 14 * * ? It runs every 5 minutes from 14:00 to 15:00 every day, starting at 14:00 and ending at 14:55.
0 0/5 14,18 * * ? Run every 5 minutes from 14:00 to 15:00 every day, and every 5 hours from 18:00 to 19:00 every day.
0 0-5 14 * * ? Run every minute from 14:00 to 14:05 every day.
0 0-5/2 14 * * ? Run every 2 minutes from 14:00 to 14:05 every day.
0 10,44 14 ? 3 4 At 14:10 and 14:44 on every Wednesday in March, it runs once respectively.
0 15 10 ? * 2-6 It runs every Monday, Tuesday, Wednesday, Thursday and Friday at 10:15.
0 15 10 15 * ? It runs at 10:15 on the 15th of each month.
0 15 10 L * ? It runs at 10:15 on the last day of each month.
0 15 10 ? * 6L It runs at 10:15 on the last Friday of each month. [at this time, the day must be "?"]
0 15 10 ? * 6L 2007-2009 It runs at 10:15 on the last Friday of each month in 2007, 2008 and 2009.

4, Spring integrates Quartz [key points]

4.1 dependence

<dependencies>
    <dependency>
        <groupId>org.quartz-scheduler</groupId>
        <artifactId>quartz</artifactId>
        <version>2.3.2</version>
    </dependency>
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.2.6.RELEASE</version>
    </dependency>
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.2.6.RELEASE</version>
    </dependency>
</dependencies>

4.2 Job definition

Define a Job class

public class MyJob implements Job {
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.err.println("job implement"+new Date());
    }
}

4.3 configure ApplicationContext xml

Scheduler SchedulerFactoryBean

Trigger CronTriggerFactoryBean

JobDetail JobDetailFactoryBean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--
        Spring integration Quartz To configure, follow the steps below:
        1: Define the of work tasks Job
        2: Define trigger Trigger,And bind the trigger to the work task
        3: Define the scheduler and Trigger Register to Scheduler
     -->

    <!-- 1: Define the of the task bean ,Use here JobDetailFactoryBean,You can also use MethodInvokingJobDetailFactoryBean ,Configuration similar-->
    <bean name="lxJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <!-- appoint job Name of -->
        <property name="name" value="job1"/>
        <!-- appoint job Grouping of -->
        <property name="group" value="job_group1"/>
        <!-- Specify specific job class -->
        <property name="jobClass" value="com.qf.quartz.MyJob"/>
    </bean>

    <!-- 2: Defines the of the trigger bean,Define a Cron of Trigger,A trigger can only be bound to one task -->
    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <!-- appoint Trigger Name of -->
        <property name="name" value="trigger1"/>
        <!-- appoint Trigger Name of -->
        <property name="group" value="trigger_group1"/>
        <!-- appoint Tirgger Bound JobDetail -->
        <property name="jobDetail" ref="lxJob"/>
        <!-- appoint Cron The current expression is every 5 s Run once -->
        <property name="cronExpression" value="*/5 * * * * ?" />
    </bean>

    <!-- 3.Define the scheduler and Trigger Register with scheduler -->
    <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="cronTrigger"/>
            </list>
        </property>
        <!-- add to quartz Configuration, the following two methods can be used -->
        <!--<property name="configLocation" value="classpath:quartz.properties"></property>-->
        <property name="quartzProperties">
            <value>
                # Specify the name of the scheduler. The actual type is QuartzScheduler
                org.quartz.scheduler.instanceName = MyScheduler
                # Specify connection pool
                org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
                # Number of connection pool threads
                org.quartz.threadPool.threadCount = 11
                # priority
                org.quartz.threadPool.threadPriority = 5
                # Non persistent job
                org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore
            </value>
        </property>
    </bean>
</beans>

4.4 operation

4.4.1 start task

The factory starts, the scheduler starts, and the task scheduling starts

public static void main(String[] args) throws InterruptedException, SchedulerException {	
    // Plant start, task start, plant close, task stop
	ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
}
4.4.2 task operation
4.4.2.1 delete task
public static void main(String[] args) throws InterruptedException, SchedulerException {		
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    System.out.println("=============");
    StdScheduler scheduler = (StdScheduler) context.getBean("scheduler");
    System.out.println(scheduler.getClass());
    Thread.sleep(3000);
    // Delete Job
    scheduler.deleteJob(JobKey.jobKey("job1","job_group1"));
}
4.4.2.2 suspension and resumption
public static void main(String[] args) throws InterruptedException, SchedulerException {		
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    System.out.println("=============");
    StdScheduler scheduler = (StdScheduler) context.getBean("scheduler");
    System.out.println(scheduler.getClass());
    Thread.sleep(3000);
    // Suspend and resume work
    scheduler.pauseJob(JobKey.jobKey("job1","job_group1"));// Suspend work
    Thread.sleep(3000);
    scheduler.resumeJob(JobKey.jobKey("job1","job_group1"));// Resume work
}
4.4.2.3 batch operation
public static void main(String[] args) throws InterruptedException, SchedulerException {		
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    System.out.println("=============");
    StdScheduler scheduler = (StdScheduler) context.getBean("scheduler");
    System.out.println(scheduler.getClass());
    Thread.sleep(3000);
    GroupMatcher<JobKey> group1 = GroupMatcher.groupEquals("job_group1");
    scheduler.pauseJobs(group1); // Pause all work in the group
    Thread.sleep(2000);
    scheduler.resumeJobs(group1); // Restore all work in the group 
}

Tags: Quartz

Posted by koddos on Sat, 21 May 2022 08:22:29 +0300