定义ScheduledProperties
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@Getter
@Setter
@ConfigurationProperties(prefix = "pic-scheduling")
public class ScheduledProperties{
private Boolean enable = true;
private String taskCronTrigger;
}
配置定时任务
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
@Component
@Slf4j
public class ScheduledTask implements InitializingBean {
private static ScheduledFuture<?> future = null;
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
@Resource
private ScheduledProperties scheduledProperties;
private static final String SCHEDULED_PREFIX = "pic-scheduling";
/**
* 监听定时任务配置
*/
@EventListener
public void envChangeListener(EnvironmentChangeEvent event) {
Set<String> keys = event.getKeys();
if (CollectionUtils.isNotEmpty(keys)) {
// 判断是否修改了定时任务的配置
boolean flag = keys.stream().anyMatch(x -> x.startsWith(SCHEDULED_PREFIX));
if (flag) {
log.info("The configuration of the scheduled task is changed. Procedure");
// 若已存在该定时任务,则停止重新创建
if (Objects.nonNull(future)) {
future.cancel(true);
}
this.syncExec();
}
}
}
/**
* 创建定时任务
*/
public void syncExec() {
log.info("pic-scheduling.enable: {}", scheduledProperties.getEnable());
if (Objects.equals(scheduledProperties.getEnable(), true)) {
future = threadPoolTaskScheduler.schedule(() -> {
try {
log.info("开始执行定时任务");
} catch (Exception e) {
log.error("定时任务执行异常:", e);
}
}, triggerContext -> {
String cron = scheduledProperties.getTaskCronTrigger();
if (StringUtils.isEmpty(cron)) {
cron = "0 0/30 * * * ? "; //默认配置:每30分钟执行一次
}
return new CronTrigger(cron).nextExecutionTime(triggerContext);
});
} else {
log.info("Canceling a scheduled task");
if (Objects.nonNull(future)) {
future.cancel(true);
}
}
}
@Override
public void afterPropertiesSet() {
taskScheduler();
this.syncExec();
}
public void taskScheduler() {
if (threadPoolTaskScheduler == null) {
// 自定义线程池
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(3);
scheduler.setThreadNamePrefix("picture-thread");
scheduler.setAwaitTerminationSeconds(600);
scheduler.setWaitForTasksToCompleteOnShutdown(true);
threadPoolTaskScheduler = scheduler;
threadPoolTaskScheduler.initialize();
}
}
}