工具类
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
public class CronTaskRegistrar implements DisposableBean {
@Override
public void destroy() throws Exception {
for (ScheduledTask task : this.scheduledTasks.values()) {
task.cancel();
}
this.scheduledTasks.clear();
}
private final Map<String, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);
@Autowired
private TaskScheduler taskScheduler;
public TaskScheduler getScheduler() {
return this.taskScheduler;
}
/**
* 新增定时任务
* @param task
* @param cronExpression
*/
public void addCronTask(String taskId,Runnable task, String cronExpression) {
addCronTask(taskId,new CronTask(task, cronExpression));
}
public void addCronTask(String taskId,CronTask cronTask) {
if (cronTask != null) {
if (this.scheduledTasks.containsKey(taskId)) {
removeCronTask(taskId);
}
this.scheduledTasks.put(taskId, scheduleCronTask(cronTask));
}
}
/**
* 移除定时任务
*/
public void removeCronTask(String taskId) {
ScheduledTask scheduledTask = this.scheduledTasks.remove(taskId);
if (scheduledTask != null){
scheduledTask.cancel();}
}
public ScheduledTask scheduleCronTask(CronTask cronTask) {
ScheduledTask scheduledTask = new ScheduledTask();
scheduledTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
return scheduledTask;
}
}
静态配置
import java.util.concurrent.ScheduledFuture;
public final class ScheduledTask {
public volatile ScheduledFuture<?> future;
/**
* 取消定时任务
*/
public void cancel() {
ScheduledFuture<?> future = this.future;
if (future != null) {
future.cancel(true);
}
}
}
启动配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@EnableScheduling
@Configuration
public class SchedulingConfig {
@Bean
public TaskScheduler taskScheduler() {
// 创建任务调度线程池
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
// 初始化线程池数量
taskScheduler.setPoolSize(5);
// 是否将取消后的任务,从队列中删除
taskScheduler.setRemoveOnCancelPolicy(true);
// 设置线程名前缀
taskScheduler.setThreadNamePrefix("TaskSchedulerThreadPool-");
return taskScheduler;
}
}
代码
//删除任务
try {
registrar.removeCronTask(taskId);
} catch (Exception e) {
e.printStackTrace();
}
//启动任务
registrar.addCronTask(qo.getId(),doTask(entity),corn);
private Runnable doTask(ScheduledConfigEntity entity) {
task = new Runnable() {
@SneakyThrows
@Override
public void run() {
//todo
//发送推送
}
};
return task;
}