weixin_慕前端4079947
2019-06-27 20:26:43浏览 1533
package com.huihe.exam.task;
import com.huihe.exam.ServiceExamApplication;
import com.huihe.exam.mapper.ScheduleMapper;
import com.huihe.exam.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
/**
* 调度主任务,负责扫描待执行任务表,将即将要(1分钟内)执行的任务加入到任务池
*/
@Component
public class TaskAdmin {
private final Logger log = LoggerFactory.getLogger(TaskAdmin.class);
public static final Map<String, ScheduledFuture> scheduledFutureMap = new ConcurrentHashMap<>();
@Autowired
ThreadPoolTaskScheduler threadPoolTaskScheduler;
@Autowired
ScheduleMapper mapper;
@Scheduled(cron = "0 0/1 * * * *")
public void task() {
log.info("查询未执行任务");
List<SchedulerTask> taskList = mapper.getUnExecuteTask();
handleTasks(taskList);
}
public void handleTasks(List<SchedulerTask> taskList) {
for (SchedulerTask schedulerTask : taskList) {
AbstractTask task = (AbstractTask) ServiceExamApplication.applicationContext.getBean(schedulerTask.getClassName());
String taskId = schedulerTask.getId();
if(null != task){
task.setTask(schedulerTask);
if(!scheduledFutureMap.containsKey(taskId)){
task.doing();
if(DateUtil.isBeforeNow(schedulerTask.getStartTime())) {
log.info("执行run方法");
task.run();
} else {
scheduledFutureMap.put(taskId, threadPoolTaskScheduler.schedule(task, task.getTrigger()));
log.info("任务【{}:{}】加入到任务池,当前任务池长度:{}", schedulerTask.getTaskName(), schedulerTask.getId(), scheduledFutureMap.size());
}
}
} else {
log.error("初始化子任务【{}:{}】出错", schedulerTask.getClassName(), taskId);
}
}
}
}