Spring boot uses Quartz timer to perform multiple timing tasks configuration

First of all, before the beginning of the article, I will put an article about simple use of timer in Springboot:
https://blog.csdn.net/qq_35387940/article/details/82800403

In fact, the above article has satisfied most of the situations, and it is a very concise way to use annotations.

 

Now this is a more traditional manual configuration:
Scheduled task configuration includes:

jobDetail task instance specific content of scheduled task execution, etc. - related business code

Trigger trigger setting related run cycle and so on - binding task instance (this article will introduce two kinds of triggers, simple and setting cron)

Scheduler scheduler determines which scheduled tasks will execute - bind triggers

 

OK, let's start.

First, import the related dependency packages that will be used by Quartz timer:

        <!-- scheduled The resources are spring-context-support,stay Spring Middle pair Quartz Is integrated in spring-context-support In the bag.
         org.springframework.scheduling.quartz
      -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <!-- Quartz coordinate -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
            <!-- Quartz Default requirement slf4j Support. springboot , a later version of slf4j -->
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-api</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>

Then look at the overall documents we need to get in this practice:

Create an instance of the first scheduled task, TaskJobOne.class: (note @ enableschedulent here)

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import java.util.Date;
import static java.lang.Thread.sleep;

/**
 * @Author : JCccc
 * @CreateTime : 2020/3/9
 * @Description :
 **/
@Component
@EnableScheduling
public class TaskJobOne {


    public  void testJobOneMethod() throws InterruptedException {
        System.out.println("1  Timed task 1 is in progress......"+new Date());
        sleep(1000);

        System.out.println("1  Timed task 1 business code execution completed......"+new Date());
    }
}

Then create multiple instances of the second scheduled task, TaskJobTwo.class: (note @ enableschedulement here)

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import java.util.Date;
import static java.lang.Thread.sleep;

/**
 * @Author : JCccc
 * @CreateTime : 2020/3/9
 * @Description :
 **/

@Component
@EnableScheduling
public class TaskJobTwo {


    public  void testJobTwoMethod() throws InterruptedException {
        System.out.println("2  Timed task 2 in progress......" + new Date());
        sleep(1000);

        System.out.println("2  Timed task 2 business code execution completed......"+new Date());
    }
    
}

 

Then bind triggers to these task instances, and add triggers to the scheduling factory:

Create QuartzConfiguration.class:

(pay attention to the notes for each step, or see my brief key point description later!)

import com.demo.elegant.quartz.taskOne.TaskJobOne;
import com.demo.elegant.quartz.taskTwo.TaskJobTwo;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;
import java.util.Date;

/**
 * @Author : JCccc
 * @CreateTime : 2020/3/9
 * @Description :
 **/

@Configuration
public class QuartzConfiguration {




/*
Scheduled task configuration includes:
    jobDetail Task instance
    Specific content of scheduled task execution - related business code
    trigger trigger
    Set related running cycle - bind task instance
    scheduler Scheduler
    Decide which scheduled tasks will execute - bind triggers
*/

    /**
     * Scheduled task 1
     */

    // Configure task instances for timed task 1
    @Bean(name = "firstJobDetail")

    public MethodInvokingJobDetailFactoryBean firstJobDetail(TaskJobOne taskJobOne) {
        MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean();
        // Concurrent execution or not
        jobDetail.setConcurrent(false);
        // Object corresponding to the entity class to be executed
        jobDetail.setTargetObject(taskJobOne);
        // Methods to be implemented
        jobDetail.setTargetMethod("testJobOneMethod");
        return jobDetail;
    }


    // Configure trigger 1
    @Bean(name = "firstTrigger")
    public SimpleTriggerFactoryBean firstTrigger(JobDetail firstJobDetail) {
        SimpleTriggerFactoryBean trigger = new SimpleTriggerFactoryBean();
        trigger.setJobDetail(firstJobDetail);
        // Set task start delay
        trigger.setStartDelay(0);
        // Set scheduled task start time
        trigger.setStartTime(new Date());
        // Every 5 seconds
        trigger.setRepeatInterval(5000);
        return trigger;
    }


    /**
     * Timed task 2
     *
     * @param taskJobTwo
     * @return
     */

    // Configure task instances for timed task 2
    @Bean(name = "secondJobDetail")
    public MethodInvokingJobDetailFactoryBean secondJobDetail(TaskJobTwo taskJobTwo) {
        MethodInvokingJobDetailFactoryBean jobDetail = new MethodInvokingJobDetailFactoryBean();
        // Concurrent execution or not
        jobDetail.setConcurrent(true);
        // Object corresponding to the entity class to be executed
        jobDetail.setTargetObject(taskJobTwo);
        // Methods to be implemented
        jobDetail.setTargetMethod("testJobTwoMethod");
        return jobDetail;
    }

    // Configure trigger 2
    @Bean(name = "secondTrigger")
    public CronTriggerFactoryBean secondTrigger(JobDetail secondJobDetail) {
        CronTriggerFactoryBean trigger = new CronTriggerFactoryBean();
        trigger.setJobDetail(secondJobDetail);
        // Set scheduled task start time
        trigger.setStartTime(new Date());
        // cron expressions 
        trigger.setCronExpression("*/7 * * * * ?");
        return trigger;
    }


    // Configure Scheduler
    @Bean(name = "scheduler")
    public SchedulerFactoryBean schedulerFactory(Trigger firstTrigger, Trigger secondTrigger) {
        SchedulerFactoryBean bean = new SchedulerFactoryBean();
        // Delay start, 1 second after application start
        bean.setStartupDelay(1);
        // Register trigger
        bean.setTriggers(firstTrigger, secondTrigger);
        return bean;
    }


}

 

 

Key point description 1:
Configure our instance as a scheduled task instance

Key point description 2:

Bind trigger simple trigger:

 

Key point description 3:

The trigger of cron expression can be used for binding. In this practice, our task 2 is:

 

Key point description 4:

Add the configured trigger to the scheduling factory:

 

 

After running, you can see that the two scheduled tasks are running normally:

 

If you need to continue to add other timing tasks, you need to create an instance, and then bind the related configurations in the configuration file.

 

That's all.  

156 original articles published, 228 praised, 200000 visitors+
Private letter follow

Tags: Java Spring SpringBoot

Posted on Mon, 09 Mar 2020 01:17:00 -0400 by magnetica