Project training record (eight) - springboot timing task

Table of contents

1. What did you do?

2. How SpringBoot performs scheduled tasks

1. Applicable scenarios

2. Dynamic - based on the interface (SchedulingConfigurer) to achieve timing tasks

step1: Store the task execution cycle in the database

Step2: Add pom.xml configuration information (this is not needed if the project has been configured before)

Step3: Configure the data source (you don’t need to configure it if you have configured it)

step4: Create a timer

1. What did you do?

It's early June, and I'm about to go to the project defense.

Now to further improve the function. Because it is an information office data sorting system, the data of the information system needs to be backed up in time.

The current plan is to make scheduled backups. Here I am responsible for creating timed tasks. Then call the database backup method.

Because it is the springboot framework, a dynamic interface-based method is finally used. Let's talk about how to do it.

2. How SpringBoot performs scheduled tasks

1. Applicable scenarios

Once a day, once a week, once a month, once a year, do daily, weekly, monthly, annual report statistics, and information reminders, etc., spring boot provides three ways to implement timing tasks.

  • 1. Static - based on annotations (@Scheduled)
  • Two, dynamic - based on the interface (SchedulingConfigurer)
  • 3. Set multi-threaded timing tasks based on annotations

Several methods of analysis:

serial number Way advantage shortcoming
1 Static - based on annotations (@Scheduled) The @Scheduled annotation is very convenient, and the default is single-threaded

① When multiple tasks are enabled, the execution timing of the task will be affected by the execution time of the previous task

②The project needs to be restarted when modifying the timing time

2 Dynamic - interface-based (SchedulingConfigurer)

①It can take effect without restarting the project

cronPersist the expression to the database

① If there is an error in the format when the database is modified, the scheduled task will stop even if the modification is correct; at this time, the project can only be recovered by restarting the project

3 Set multi-threaded timed tasks based on annotations

①Multi-threading between multiple tasks can be solved by configuring the thread pool

②Single-task and multi-threading can be @Asyncsolved, and the thread pool can be directly specified@Async("taskExecutor")

@Async reference

2. Dynamic - based on the interface (SchedulingConfigurer) to achieve timing tasks

step1: Store the task execution cycle in the database

The code is as follows (creating a cron table, inserting the first task execution cycle is 5ms):

DROP TABLE IF EXISTS cron;
CREATE TABLE cron  (
  cron_id VARCHAR(30) NOT NULL PRIMARY KEY,
  cron VARCHAR(30) NOT NULL  
);
 
INSERT INTO cron VALUES ('1', '0/5 * * * * ?');

step2: Add pom.xmlconfiguration information (this is not needed if the project has been configured before)

code show as below:

<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
</dependency>

<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
</dependency>

Step3: Configure the data source (you don’t need to configure it if you have configured it)

code show as below:

spring.datasource.dynamic.datasource.student.url=jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.dynamic.datasource.student.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.dynamic.datasource.student.username=root
spring.datasource.dynamic.datasource.student.password=xxx

step4: Create a timer

4.1 Create Cron class, CronMapper class and CronMapper.xml

Cron class

package com.example.server.domain;

import lombok.Data;

@Data
public class Cron {
    int cronid;
    String cron;
}

CronMapper class

package com.example.server.mapper;


import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface CronMapper {

    String getCron();
}

CronMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.server.mapper.CronMapper" >
    <resultMap id="BaseResultMap" type="com.example.server.domain.Cron" >
        <!--
          WARNING - @mbggenerated
          This element is automatically generated by MyBatis Generator, do not modify.
        -->
        <!--        首先需申明数据库表和domain之间的对应关系-->
        <id column="cron_id" property="cronid" jdbcType="INTEGER" />
        <result column="cron" property="cron" jdbcType="VARCHAR" />
    </resultMap>

    <sql id="Base_Column_List">
        cron_id,cron
    </sql>
    <resultMap id="cronResult" type="java.lang.String">
        <result column="cron" property="cron" jdbcType="VARCHAR" />
    </resultMap>

    <select id="getCron" resultMap="cronResult">
        select cron from cron
    </select>


</mapper>

4.2 Create a class in the controller layer

package com.example.server.controller;


import com.example.server.mapper.CronMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 动态定时任务配置类
 */
@Configuration //标记配置类,兼备Component的效果
@EnableScheduling //开启定时任务
public class SimpleScheduleConfig implements SchedulingConfigurer{

    @Autowired
    CronMapper cronMapper;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar){
        Thread thread = new Thread(){
            @Override
            public void run() {
                super.run();
               
                System.out.println("定时发送线程启动:" + LocalDateTime.now().toLocalTime());
            }
        };

        taskRegistrar.addTriggerTask(
                thread,
                triggerContext -> {
                    //从数据库获取执行周期
                    String cron = cronMapper.getCron();
                    //非空校验
                    if(StringUtils.isEmpty(cron)){
                        //TODO
                    }
                    //返回执行周期
                    //在这里进行备份方法调用
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );

    }
}

4.2 Start scheduled tasks

Add annotation @EnableScheduling //Enable scheduled tasks

package com.example.server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling //开启定时任务
public class ServerApplication {

    public static void main(String[] args) {
        //SpringApplication.run(ServerApplication.class, args);
        SpringApplication.run(ServerApplication.class, args);
    }

}

Done!

Guess you like

Origin blog.csdn.net/pinkray_c/article/details/125117013