package com.xxx.framework.task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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.stereotype.Component;
import java.util.Date;
@Component
public class XXXTask implements SchedulingConfigurer {
private static final Logger log = LoggerFactory.getLogger(XXXTask.class);
// 判断是否第一次运行
private boolean firstTime = true;
// 第一次执行的cron表达式
private String cron = "* 0/1 * * * ?";
// 定时任务是否开启的标识
@Value("${xxx.task-enabled}")
private boolean taskEnabled;
// 定时任务正常运行时的cron表达式
@Value("${xxx.task-cron}")
private String runtimeCron;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(new Runnable() {
@Override
public void run() {
log.info("XXXTask Begin.");
if(taskEnabled) {
// 业务
}
log.info("XXXTask End.");
if(firstTime){
firstTime = false;
setCron(runtimeCron);
}
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
return new CronTrigger(cron).nextExecutionTime(triggerContext);
}
});
}
public void setCron(String cron) {
this.cron = cron;
}
}
Springboot定时任务的一种写法
最新推荐文章于 2024-11-07 17:23:13 发布