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); } } } }
点击查看更多内容
1人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦