This is the 29th day of my participation in the August More Text Challenge

In the previous article, you learned how to implement Scheduled tasks in SpringBoot using the @scheduled annotation: SpringBoot uses @scheduled to create Scheduled tasks

Although it is convenient to configure Scheduled tasks using the @scheduled annotation, because it is set in annotations, any changes to the Scheduled schedule of the current task will require a project restart to take effect. To solve this problem of not being able to change in time, we can implement the interface to complete the creation of scheduled tasks.

Introduction of depend on

Periodic task rules cannot be written into the code because they need to be modified in real time. Therefore, periodic task rules are written into the database. Each time a periodic task is executed, the latest rules in the database are obtained and added to the task. We need to use database in the project, so we need to introduce MySQl, MyBatis and other dependency information:

<dependency>
     <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.5</version>
    <scope>compile</scope>
</dependency>
Copy the code

The task rule table and data are added to the database

Add a task table to the local database to record rules about scheduled tasks.

CREATE TABLE `task`  (
  `id` int NOT NULL PRIMARY KEY,
  `cron` varchar(30) NOT NULL  
);
INSERT INTO `task` VALUES (1.'* * *? *? ');
Copy the code

Select * * *? From ‘* * *? *? ‘as you can see, our timed task rule for adding data is executed once per second. Then configure the data source information in the configuration file of the SpringBoot project:

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.. password=123456
Copy the code

Creating a Timer class

With the data ready and data source information configured, we define a timer class on which to start a scheduled task with the @enablesCheduling annotation.

@Configuration
@EnableScheduling 
public class TaskDemo implements SchedulingConfigurer {
    @Mapper
    public interface CronMapper {
        @Select("select cron from cron limit 1")
        public String getCron(a);
    }

    @Autowired 
    @SuppressWarnings("all")
    CronMapper cronMapper;

    /** * Performs scheduled tasks. */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(
                () -> System.out.println("Execute a dynamic scheduled task:" + LocalDateTime.now().toLocalTime()),
                triggerContext -> {
                    String cron = cronMapper.getCron();
                    if (StringUtils.isEmpty(cron)) {
                        
                    }
                    return newCronTrigger(cron).nextExecutionTime(triggerContext); }); }}Copy the code

Test scheduled Task

After the configuration is complete, we start the project and find that the scheduled task executes output at the set rate per second, whereas if we change the cron field in the database to ‘0/5 * *? *? ‘, the scheduled task rules automatically change. If the final modified value does not conform to the CRon expression specification, the timer class reports an error and stops execution.