Dynamic Configuration of Modifying Execution Time Using spring task Timing Tasks

  • 2021-12-09 08:49:33
  • OfStack

Directory spring-task Timing Task Dynamic Configuration Modification Execution Time spring schedule Dynamic Configuration Execution Time

spring-task Timing Task Dynamic Configuration Modification Execution Time

Due to the needs of the project, several timed tasks need to set the execution time artificially dynamically, so, just consult the relevant information, which can be set dynamically. Needless to say, go directly to the code, and see clearly.


package com.seckill.quartz;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
 
/**
 * Created by loup on 2017/11/11.
 */
@Component
@EnableScheduling
public class DynamicScheduledTask implements SchedulingConfigurer {
    // Time expression    Every 2 Second execution 1 Times 
    private String cron = "0/2 * * * * ?";
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                // Task logic 
                System.out.println("---------------start-------------------");
                System.out.println(" Dynamic modification of timing task parameters and time expressions cron Is: " + cron);
                System.out.println(" The current time is: " + sdf.format(new Date()));
                System.out.println("----------------end--------------------");
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                CronTrigger cronTrigger = new CronTrigger(cron);
                Date nextExecDate = cronTrigger.nextExecutionTime(triggerContext);
                return nextExecDate;
            }
        });
    }
 
    public void setCron(String cron) {
        this.cron = cron;
    }
}

This is a timed task scheduling executor, which uses annotation. First of all, it should be dynamically configured, set to @ EnableScheduling, which is to ensure that it can be dynamically, then implement SchedulingConfigurer, rewrite configureTasks method, and then it is the related spring configuration file. It is necessary to introduce the following task, otherwise it will not be recognized. The configuration file is as simple as that

http://www.springframework.org/schema/task


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:task="http://www.springframework.org/schema/task"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 
    <context:component-scan base-package="com.seckill.quartz"/> 
    <task:annotation-driven /> 
</beans>

The next step is to write a test class. Is the test feasible?


package com.seckill.quartz;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.IOException;
 
/**
 * Created by loup on 2017/11/11.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath*:/conf/spring-quartz.xml"})
public class QuartzTest {
 
    @Autowired
    private DynamicScheduledTask dynamicScheduledTask;
 
    @Test
    public void test1(){
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        dynamicScheduledTask.setCron("0/10 * * * * ?");
        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Run the test class, view the results, achieve the effect, and the pro-test is available

spring schedule Dynamic Configuration Execution Time

Previously, saas platform realized dynamic modification of timing task time, They are all implemented through the framework of xx-job. In this way, we can manage the timing tasks of our whole saas platform with a single service, but a small project recently done for the bank needs localized deployment, so I don't want to get a lot of services, and they don't require immediate effect after modification, so I directly adopted spring schedule combined with mysql to dynamically configure the execution time.

The schedule we used before can only use static corn expressions by annotation. If we want to realize dynamic SchedulingConfigurer, we need to realize it by annotation @ EnableScheduling. As follows:


package com.zqf.marketing.task;  
import com.zqf.db.marketingrobot.sys.model.RobotSysSwitch;
import com.zqf.marketing.sys.service.SwitchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service; 
import java.util.Date;
 
/**
 * @author zhenghao
 * @description
 * @date 2019/1/22 21:50
 */
 
@Lazy(false)
@Service
@EnableScheduling
public class TestTaskService implements SchedulingConfigurer { 
    private static Logger log = LoggerFactory.getLogger(TestTaskService.class);
    @Autowired
    private SwitchService switchService;  
    private String SpringDynamicCronTask() {
        String cron = "0/5 * * * * ?";
        // Object to get the configuration from the database corn Expression 
        RobotSysSwitch switchById = switchService.getSwitchById(5L);
        cron = switchById.getSwitchFlag();
        log.info(cron);
        return cron;
    } 
 
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                //  Task logic 
                log.info("task_task_tak");
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                String s = SpringDynamicCronTask();
                //  Task triggering, which can modify the execution cycle of a task 
                CronTrigger trigger = new CronTrigger(s);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        });  
    }
}

In this way, we can dynamically modify the task execution time, effective time, the last 1 task execution cycle, can also meet our current needs, so that the internship project is more flexible!


Related articles: