Springboot integrates quartz to implement dynamic modification, startup, suspension and other operations of scheduled tasks.

What is Quartz?

A scheduled task scheduling framework that is simple to use and powerful enough to implement scheduled tasks. During the project development process, some scheduled tasks may no longer be needed after running for a period of time, or the execution time of the scheduled tasks may need to be modified, etc. It needs to be modified in the code and then repackaged and released, which is very troublesome. If you use Quartz to implement it, you don’t need to re-modify the code to meet the requirements.

springboot integrates Quartz timing scheduling framework

Development environment

  1. JDK version 1.8
  2. springboot version: 2.1.0
  3. Development tools: IDEA

Implement a simple scheduled task

The first step is to introduce the corresponding jar

After springboot2.0, the dependency of Quartz framework was officially added, so it only needs to be introduced in the pom file.

 <!--Introducing the quartz timing framework-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-quartz</artifactId>
        </dependency>

Step 2: Create a scheduled task

Since springboot2.0 automatically relies on it, the created scheduled task class can directly inherit QuzrtzJobBean. Create a new scheduled task class: MyTask

public class MyTask extends QuartzJobBean {
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //TODO Write the execution logic of the scheduled task here
        System.out.println("Simple scheduled task execution time:" + new Date().toLocaleString());
    }
}

The third step is to create a Quartz configuration class and add the previously created scheduled tasks to the scheduled schedule

@Configuration
public class QuartzConfig {
//Specify a specific scheduled task class
    @Bean
    public JobDetail uploadTaskDetail() {
        return JobBuilder.newJob(MyTask.class).withIdentity("MyTask").storeDurably().build();
    }

    @Bean
    public Trigger uploadTaskTrigger() {
        //TODO sets the execution method here
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("*/5 * * * * ?");
        //Return task trigger
        return TriggerBuilder.newTrigger().forJob(uploadTaskDetail())
                .withIdentity("MyTask")
                .withSchedule(scheduleBuilder)
                .build();
    }
}

Finally run the project to see the effect

Successful execution of tasks

This method is hard-coded into the program and may be inconvenient to modify! ! ! ! ! !

Achieve dynamic suspension, modification, startup, single execution and other operations of scheduled scheduling tasks

The first step is to create a scheduled task-related entity class to save scheduled task-related information to the database

public class QuartzBean {
    /** task id */
    private String id;

    /** mission name */
    private String jobName;

    /** Task execution class */
    private String jobClass;

    /** Task status: start or pause*/
    private Integer status;

    /** Task running time expression */
    private String cronExpression;
    //Omit getter setter
  }

Step 2: Create scheduled task pause, modify, start, and single start tool classes

public class QuartzUtils {

    /**
     * Create a scheduled task. After the scheduled task is created, it will start in the default state.
     * @param scheduler scheduler
     * @param quartzBean scheduled task information class
     * @throwsException
     */
    public static void createScheduleJob(Scheduler scheduler, QuartzBean quartzBean){
        try {
            //Get the execution class of the scheduled task. It must be the absolute path name of the class.
            //The scheduled task class needs to be a concrete implementation of the job class. QuartzJobBean is the abstract class of job.
            Class<? extends Job> jobClass = (Class<? extends Job>) Class.forName(quartzBean.getJobClass());
            //Construct scheduled task information
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(quartzBean.getJobName()).build();
            //Set the scheduled task execution method
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzBean.getCronExpression());
            //Build trigger trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(quartzBean.getJobName()).withSchedule(scheduleBuilder).build();
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (ClassNotFoundException e) {
            System.out.println("Scheduled task class path error: Please enter the absolute path of the class");
        } catch (SchedulerException e) {
            System.out.println("Error creating scheduled task:" + e.getMessage());
        }
    }

    /**
     * Pause the scheduled task according to the task name
     * @param scheduler scheduler
     * @param jobName Scheduled task name
     * @throws SchedulerException
     */
    public static void pauseScheduleJob(Scheduler scheduler, String jobName){
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.pauseJob(jobKey);
        } catch (SchedulerException e) {
            System.out.println("Error in pausing scheduled task:" + e.getMessage());
        }
    }

    /**
     *Restore scheduled tasks based on task name
     * @param scheduler scheduler
     * @param jobName Scheduled task name
     * @throws SchedulerException
     */
    public static void resumeScheduleJob(Scheduler scheduler, String jobName) {
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.resumeJob(jobKey);
        } catch (SchedulerException e) {
            System.out.println("Error starting scheduled task:" + e.getMessage());
        }
    }

    /**
     * Immediately run a scheduled task based on the task name
     * @param scheduler scheduler
     * @param jobName Scheduled task name
     * @throws SchedulerException
     */
    public static void runOnce(Scheduler scheduler, String jobName){
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.triggerJob(jobKey);
        } catch (SchedulerException e) {
            System.out.println("Error running scheduled task:" + e.getMessage());
        }
    }

    /**
     * Update scheduled tasks
     * @param scheduler scheduler
     * @param quartzBean scheduled task information class
     * @throws SchedulerException
     */
    public static void updateScheduleJob(Scheduler scheduler, QuartzBean quartzBean) {
        try {
            //Get the trigger of the corresponding task
            TriggerKey triggerKey = TriggerKey.triggerKey(quartzBean.getJobName());
            //Set the scheduled task execution method
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzBean.getCronExpression());
            //Reconstruct the trigger of the task
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            //Reset the corresponding job
            scheduler.rescheduleJob(triggerKey, trigger);
        } catch (SchedulerException e) {
            System.out.println("Error updating scheduled task:" + e.getMessage());
        }
    }

    /**
     * Delete the scheduled task from the scheduler according to the scheduled task name
     * @param scheduler scheduler
     * @param jobName Scheduled task name
     * @throws SchedulerException
     */
    public static void deleteScheduleJob(Scheduler scheduler, String jobName) {
        JobKey jobKey = JobKey.jobKey(jobName);
        try {
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            System.out.println("Error deleting scheduled task:" + e.getMessage());
        }
    }
}

Step 3: Create a scheduled task and related test classes.

Create a new scheduled task MyTask1

public class MyTask1 extends QuartzJobBean {

    //Verify whether the service is successful before injecting service. Additional configuration is required in ssm before
    @Autowired
    private AccountService service;
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Account account = new Account();
        account.setId(1);
        account = service.findByAccount(account);
        System.out.println(account.toString());
        //TODO Write the execution logic of the scheduled task here
        System.out.println("Dynamic scheduled task execution time:" + new Date().toLocaleString());
    }
}

Create a new test Controller

@Controller
@RequestMapping("/quartz/")
public class QuartzController {
    //Inject task scheduling
    @Autowired
    private Scheduler scheduler;

    @RequestMapping("/createJob")
    @ResponseBody
    public String createJob(QuartzBean quartzBean) {
        try {
            //For testing, write it to death
            quartzBean.setJobClass("com.hjljy.blog.Quartz.MyTask1");
            quartzBean.setJobName("test1");
            quartzBean.setCronExpression("*/10 * * * * ?");
            QuartzUtils.createScheduleJob(scheduler,quartzBean);
        } catch (Exception e) {
            return "Creation failed";
        }
        return "Created successfully";
    }

    @RequestMapping("/pauseJob")
    @ResponseBody
    public String pauseJob() {
        try {
            QuartzUtils.pauseScheduleJob (scheduler,"test1");
        } catch (Exception e) {
            return "Pause failed";
        }
        return "Pause successful";
    }

    @RequestMapping("/runOnce")
    @ResponseBody
    public String runOnce() {
        try {
            QuartzUtils.runOnce (scheduler,"test1");
        } catch (Exception e) {
            return "Failed to run once";
        }
        return "Run once successfully";
    }

    @RequestMapping("/resume")
    @ResponseBody
    public String resume() {
        try {

            QuartzUtils.resumeScheduleJob(scheduler,"test1");
        } catch (Exception e) {
            return "Start failed";
        }
        return "Start successfully";
    }

    @RequestMapping("/update")
    @ResponseBody
    public String update(QuartzBean quartzBean) {
        try {
            //For testing, write it to death
            quartzBean.setJobClass("com.hjljy.blog.Quartz.MyTask1");
            quartzBean.setJobName("test1");
            quartzBean.setCronExpression("10 * * * * ?");
            QuartzUtils.updateScheduleJob(scheduler,quartzBean);
        } catch (Exception e) {
            return "Start failed";
        }
        return "Start successfully";
    }
}

Then enter the corresponding URL on the web page to perform operations such as pausing, starting, creating, modifying, and running once.

Step 4 Summary

1 After springboot2.0, quartz dependency is added by default, which can save a lot of configuration information. You only need to write your own task class (you need to implement the job class) and then add tasks through the scheduler. 2 When simply creating a scheduled task through the @Bean annotation, you can directly write the class of the task class, but when using the scheduler, you need to write the absolute name. 3 When the quartz task is started again after being paused, it will be executed once, and it will be executed immediately after the update. 4 The default quartz thread pool size in springboot is 10. 5 When starting the project initialization, the scheduled tasks of the project need to be initialized as well. This is more convenient and does not need to be started in sequence.

Reference materials

Springboot integrates Quartz scheduled tasks: https://www.cnblogs.com/lic309/p/4089633.html springboot official manual: https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference /html/boot-features-quartz.html

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 138175 people are learning the system