Bootstrap

动态定时任务

动态定时任务

package com.kevin.cron.controller;

import com.kevin.cron.task.ScheduleTask;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @program: spring-boot-demo2
 * @description:
 * @author: KevinJee
 * @create: 2022-12-06 16:04
 **/
@RestController
@RequestMapping("/test")
public class TestController {
    private static final Logger logger = LoggerFactory.getLogger(TestController.class);//slf4j 日志记录器

    @Resource
    private ScheduleTask scheduleTask;

//    @Autowired
//    public TestController(ScheduleTask scheduleTask) {
//        this.scheduleTask = scheduleTask;
//    }

    @GetMapping("/updateCron")
    public String updateCron(@RequestParam String cron) {
        logger.info("new cron :{}", cron);
        scheduleTask.setCron(cron);
        return "ok";
    }
}
package com.kevin.cron.task;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
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.time.LocalDateTime;
import java.util.Date;

/**
 * @program: spring-boot-demo2
 * @description:
 * @author: KevinJee
 * @create: 2022-12-06 16:05
 **/
@Data
@Component
public class ScheduleTask implements SchedulingConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(ScheduleTask.class);//slf4j 日志记录器

    private String cron= "0/2 * * * * ?";

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        // 动态使用cron表达式设置循环间隔
        taskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                logger.info("Current time: {}", LocalDateTime.now());
            }
        }, triggerContext -> {
            // 使用CronTrigger触发器,可动态修改cron表达式来操作循环规则
            CronTrigger cronTrigger = new CronTrigger(cron);
            return cronTrigger.nextExecutionTime(triggerContext);
        });
    }
}

在这里插入图片描述

GET http://localhost:8080/test/updateCron?cron=0/5 * * * * ?

在这里插入图片描述
设定一个cron表达式的默认值,通过接口的形式进行调用传递cron表达式

;