@Component
@Slf4j
public class DynamicSchedulingTask implements SchedulingConfigurer {
private Map<String, ScheduledFuture<?>> futuresMap;
private ThreadPoolTaskScheduler threadPoolTaskScheduler;
private int poolSize = 16;
/**
* 初始化任务列表
*/
@PostConstruct
public void init() {
futuresMap = new ConcurrentHashMap<>(8);
threadPoolTaskScheduler();
}
/**
* 创建ThreadPoolTaskScheduler线程池
*/
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
this.threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(poolSize);
return threadPoolTaskScheduler;
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
threadPoolTaskScheduler.initialize();
}
/**
* 添加任务
*
* @param jobName 任务运行的唯一主键
* @param cronExp cron表达式
* @param taskType
*/
public boolean addTask(String jobName, String cronExp, int taskType) {
ScheduledFuture<?> scheduledFuture = futuresMap.get(jobName);
if (null == scheduledFuture) {
ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(new Runnable() {
@Override
public void run() {
log.info("execute time:{}", LocalDateTime.now());
//TODO 执行任务
}
}, new CronTrigger(cronExp));
ScheduledFuture oldScheduledFuture = futuresMap.put(jobName, future);
log.info("任务池任务数:{}", futuresMap.size());
if (oldScheduledFuture == null) {
return true;
}
else {
log.info("添加任务key: " + jobName + "重复");
return false;
}
}
return false;
}
public boolean removeTask(String taskId, String key) {
//需要优雅的停止,运行中需要等待,运行中完之后再remove
try {
ScheduledFuture<?> scheduledFuture = futuresMap.get(key);
if (null != scheduledFuture) {
scheduledFuture.cancel(false);
futuresMap.remove(key);
log.info("删除任务,任务池剩余长度:{}", futuresMap.size());
if (null == futuresMap.get(key)) {
log.info("stop task success,taskId:{}", taskId);
return true;
}
else {
return false;
}
}
}
catch (Exception e) {
log.error(e.getMessage(), e);
}
return false;
}
}