1、Nacos配置信息
2、 TasksScheduler文件:
package com.example.demo.utils;
import cn.hutool.core.date.DateUtil;
import com.example.demo.config.TasksConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
/**
* @author QiaoChu
*/
@Slf4j
@Component
@EnableScheduling
public class TasksScheduler {
@Resource
TasksConfig tasksConfig;
@PostConstruct
public void logConfigValues() {
log.info("OthSwitch: {}, CronExpression: {}", tasksConfig.getOthSwitch(), tasksConfig.getCronExpression());
}
@Scheduled(cron = "#{@taskConfig.cronExpression}")
public void otherTask() {
log.info("当前Cron表达式: {}", tasksConfig.getCronExpression());
log.info("OthSwitch值: {}", tasksConfig.getOthSwitch());
if (tasksConfig.getOthSwitch() == 1) {
log.info("执行,自定义计划任务,当前时间:{},执行时间:{}", DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"), tasksConfig.getCronExpression());
} else {
log.info("暂不执行,自定义计划任务,当前时间:{}", DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
}
}
public void upTask(String newCron, Integer newSwitch) {
tasksConfig.setCronExpression(newCron);
tasksConfig.setOthSwitch(newSwitch);
log.info("更新Cron表达式为: {}, OthSwitch为: {}", newCron, newSwitch);
}
}
3、TasksConfig文件:
package com.example.demo.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
/**
* @author QiaoChu
*/
@Data
@RefreshScope
@Configuration
public class TasksConfig {
// 自定义开关:1-开 0-关
@Value("${task.othSwitch}")
private Integer othSwitch;
// 自定义执行时间
@Value("${task.cronExpression}")
private String cronExpression;
}
4、TasksController文件
package com.example.demo.controller;
/**
* @author QiaoChu
*/
import com.example.demo.config.TasksConfig;
import com.example.demo.utils.TasksScheduler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping("/tasks")
public class TasksController {
@Resource
private TasksScheduler tasksScheduler;
@Resource
private TasksConfig tasksConfig;
@GetMapping("/upTask")
public String upTask() {
String newCron = tasksConfig.getCronExpression();
Integer newSwitch = tasksConfig.getOthSwitch();
tasksScheduler.upTask(newCron, newSwitch);
return String.format("Cron表达式更新为: %s, 开关值更新为: %d", newCron, newSwitch);
}
}
5、再次执行,需要在再次执行时间之前,通过浏览器访问URL地址刷新配置:http://192.168.1.108:8888/tasks/upTask
【ip:端口】
访问输出:Cron表达式更新为: 0 30 09 * * ?, 开关值更新为: 0