Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This framework can be used on top of the SpringBoot framework when SpringBoot integrates Quartz

1. Dependency introduction

Using Quartz in a SpringBoot project requires the introduction of dependency information.

<! - quartz depend on -- -- >
<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.1</version>
  </dependency>
<! -- Scheduled coordinates in SpringBoot -->
 <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context-support</artifactId>
 </dependency>
 <! --Spring tx coordinates -->
 <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-tx</artifactId>
 </dependency>
Copy the code

2. Procedure flow

  1. The task class implements the Job interface of the Quertz package and implements the execute() method to define the task content
  2. Define querTZ-related configuration classes, create JobDetailFactoryBean, SimpleTriggerFactoryBean, and SchedulerFactoryBean objects and inject them into the Spring container for management using @Bean
    • The factory class is provided by SpringBoot and exists inspring-context-supportRely on theorg.springframework.scheduling.quartzPackage, which defines the need to introduce phase dependencies when creating related objects
    • When defining JobDetailFactoryBean, you need to set the defined task class
    • The JobDetailFactoryBean object is passed in when SimpleTriggerFactoryBean is defined and the trigger policy is configured
    • The SchedulerFactoryBean definition requires passing in the SimpleTriggerFactoryBean object
  3. Use the @enablescheduing annotation on the boot class to enable the SpringBoot scheduled task
  4. After the service is started, scheduled tasks are executed based on defined policies
    • An error may occur when the service is started, so check to see if spring-TX dependencies are introduced

3. sample code

3.1 Defining a task class

The task class still implements the Job and implements the Execute interface to define the task content.

public class DoTaskTest implements Job {
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Long startTime = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Thread.sleep(2000);
            Long endTime = System.currentTimeMillis();
            System.out.println("Execute task, execute time:" + format.format(new Date(startTime)) + "Time," + (endTime-startTime));
        } catch(InterruptedException e) { e.printStackTrace(); }}}Copy the code

3.2 configuration class

Configuration classes defined when used in SpringBoot can hand over task objects, triggers, and schedulers to the Spring container for management and use as needed.

@Configuration
public class QuartzConfig {
    /** * ① Create the Job object */
    @Bean
    public JobDetailFactoryBean jobDetailFactoryBean(a){
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(DoTaskTest.class);
        return factoryBean;
    }

    /**
     * 创建Trigger对象
     */
    @Bean
    public SimpleTriggerFactoryBean simpleTriggerFactoryBean(JobDetailFactoryBean jobDetailFactoryBean){
        SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
        factoryBean.setJobDetail(jobDetailFactoryBean.getObject());
        factoryBean.setRepeatCount(10);
        factoryBean.setStartDelay(5000);
        factoryBean.setRepeatInterval(2000);
        return factoryBean;
    }

    /** * Creates a Scheduler object */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(SimpleTriggerFactoryBean simpleTriggerFactoryBean){
        SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
        factoryBean.setTriggers(simpleTriggerFactoryBean.getObject());
        returnfactoryBean; }}Copy the code

3.3 start the class

The @enablesCheduling annotation is used to start a scheduled task. It can be annotated in the startup class or Quartz configuration class.

@SpringBootApplication
@EnableScheduling
public class OctoberApplication {

    public static void main(String[] args) { SpringApplication.run(OctoberApplication.class, args); }}Copy the code

4. To summarize

It is relatively easy to integrate Quartz into a SpringBoot project so that tasks in the task class are automatically executed when the project starts.

However, in real usage scenarios, there will be more than one scheduled task, and in this case, how to define tasks, dynamically implement trigger configurations, and start and stop schedulers.