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 * * * *