目录
支持动态修改cron的定时器(SchedulingConfigurer)
基于@Scheduled的定时器
这个很简单,使用和这个注解,配置一个cron表达式,在 主类中增加一个注@EnableScheduling
即可。
这种定时器 cron表达式位置不同,分成三种。
cron配置在类中
例如:
@Scheduled(cron = "*/3 * * * * ?")
public void demo2(){
System.out.println("property cron test!");
}
启动即可跑起来,问题就是修改cron必须重新编译。
cron在配置文件中
例如
@Scheduled(cron = "${demo.test}")
public void demo(){
System.out.println("property cron test!");
}
需要在配置文件中配置:
demo:
test: '*/3 * * * * ?'
这种如果修改cron的话,不需要编译,但是如果需要cron生效的话,需要重启项目。
cron配置在数据库中
例如:
@Scheduled(cron = "#{@getCron}")
public void cancel() {
cancelDetail();
}
这里需要配置一个配置类,如下:
@Configuration
public class CronConfig {
@Autowired
private SystemSettingsDao systemSettingsDao;
@Bean
public String getCron() {
return systemSettingsDao.getSystemSettings(
"key").getPropertyValue();
}
}
这样的话,在系统启动的时候就会去加载con表达式,好处就是我们可以把多个配置项目放到一个数据库表中,集中修改,缺点还是需要重启系统使得cron生效。
支持动态修改cron的定时器(SchedulingConfigurer)
具体实现方式如下:
定义一个定时器类TestSchedulerTask 实现接口 SchedulingConfigurer,实现其中configureTasks()方法,定义触发器,在每次执行后查询最新的cron,既可支持动态cron修改而不用重启系统。
如下:
package com.iflytek.cityinsuredmonitorreport.scheduler;
import com.iflytek.cityinsuredmonitorreport.dao.SystemSettingsDao;
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.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;
import org.springframework.scheduling.support.CronTrigger;
import javax.annotation.PostConstruct;
import java.util.Date;
/**
* @Program:
* @Description:
* @Author:
* @Create: 2021-08-24 16:12
*/
@Component
@Lazy(value = false)
public class TestSchedulerTask implements SchedulingConfigurer {
private static final Logger log = LoggerFactory.getLogger(TestSchedulerTask .class);
private static String cron;
@Autowired
private SystemSettingsDao systemSettingsDao;
@Autowired
private DutyService dutyService;
//初始获取cron
@PostConstruct
public void cronInit() {
cron = getCronValue();
log.info("cron:{}", cron);
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(() -> {
// 任务逻辑
dutyService.handle();
}, triggerContext -> {
// 任务触发,可修改任务的执行周期
cron = getCronValue();
log.info("cron-new:{}", cron);
CronTrigger trigger = new CronTrigger(cron);
Date nextExec = trigger.nextExecutionTime(triggerContext);
return nextExec;
});
}
public String getCronValue() {
return systemSettingsDao.getSystemSettings(
"cron").getPropertyValue();
}
}
上述案例中 cron也是从数据库中获取,还可以支持动态修改cron,还不用重启项目。奈斯!
参考博客:
https://blog.csdn.net/G0_hw/article/details/94877687