springboot 动态配置定时任务时间
例子如下
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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;
@Component
@EnableScheduling
public class SchedulerJobs implements SchedulingConfigurer {
private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${server.scheduler.cron}")
private String cron;
@Autowired
private Service Service;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(() -> {
// 需要实现的任务逻辑
service.doWork();
logger.info("定时任务: " + "时间:【{}】",
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
}, triggerContext -> {
//任务触发,可修改任务的执行周期
CronTrigger trigger = new CronTrigger(getCron());
Date nextExec = trigger.nextExecutionTime(triggerContext);
return nextExec;
});
}
private String getCron() {
if (StringUtils.isBlank(cron)) {
cron = "0 0 * * * *";
}
return cron;
}
}
配置文件application.properties
server.scheduler.cron=0 0 * * * *