1.配置ScheduledTask
主要是实现SchedulingConfigurer,动态传入cron。
package com.hzl.boot.config;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
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.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;import java.time.LocalDateTime;
import java.util.Date;/*** @description @PropertySource:指定加载配置文件位置,@ConfigurationProperties:加载属性的前缀* @author: zhiLin* @create: 2022-09-24 21:37**/
@Data
@Component
@ConfigurationProperties("dynamic")
@PropertySource("classpath:/config/cron.properties")
public class ScheduledTask implements SchedulingConfigurer {private String test;private Long period = 500L;@Overridepublic void configureTasks(ScheduledTaskRegistrar taskRegistrar) {taskRegistrar.addTriggerTask(() -> System.out.println("Current time = "+ LocalDateTime.now()), new Trigger() {@Overridepublic Date nextExecutionTime(TriggerContext triggerContext) {// 1. 使用 cronTrigger触发器动态修改定时执行时间CronTrigger cronTrigger = new CronTrigger(test);Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext);// 2. PeriodicTrigger设置任意时间段的执行任务(另一种方式)
// PeriodicTrigger periodicTrigger = new PeriodicTrigger(period);
// Date nextExecutionTime1 = periodicTrigger.nextExecutionTime(triggerContext);return nextExecutionTime;}});}
}
2.配置执行周期
springboot的resources目录下新建/config/cron.properties,并配置如下:
dynamic.test=0/20 * * * * ?
3.编写代码
编写ScheduledController,进行测试用
package com.hzl.boot.controller;import com.hzl.boot.common.Result;
import com.hzl.boot.config.ScheduledTask;
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;/*** @description* @author: zhiLin* @create: 2022-09-24 21:56**/
@RestController
@RequestMapping("schedule")
public class ScheduledController {@Resourceprivate ScheduledTask scheduledTask;@GetMapping("/cron")public Result dynamicModifiedCron(@RequestParam String cron) {System.out.println("new cron time = " + cron);scheduledTask.setTest(cron);return Result.success();}}
4.浏览器测试
浏览器输入 http://localhost:9090/schedule/cron?cron=0/5 * * * * ?
成功将定时任务从每20秒执行改为每5秒执行