| | |
| | | import org.springframework.util.CollectionUtils; |
| | | import org.springframework.util.StringUtils; |
| | | |
| | | import javax.annotation.PreDestroy; |
| | | |
| | | import java.util.*; |
| | | import java.util.concurrent.*; |
| | | import java.util.concurrent.atomic.AtomicBoolean; |
| | | import java.util.concurrent.atomic.AtomicInteger; |
| | | |
| | | /** |
| | |
| | | |
| | | // 启动定时任务 |
| | | // 使用AtomicBoolean标记是否第一次执行 |
| | | final java.util.concurrent.atomic.AtomicBoolean firstExecution = new java.util.concurrent.atomic.AtomicBoolean(true); |
| | | final AtomicBoolean firstExecution = new AtomicBoolean(true); |
| | | |
| | | ScheduledFuture<?> future = scheduledExecutor.scheduleWithFixedDelay(() -> { |
| | | try { |
| | |
| | | return summary; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 应用关闭时清理资源 |
| | | */ |
| | | @PreDestroy |
| | | public void destroy() { |
| | | log.info("开始清理TaskExecutionEngine资源..."); |
| | | |
| | | // 停止所有定时任务 |
| | | for (Map.Entry<String, List<ScheduledFuture<?>>> entry : taskScheduledTasks.entrySet()) { |
| | | String taskId = entry.getKey(); |
| | | List<ScheduledFuture<?>> futures = entry.getValue(); |
| | | if (futures != null) { |
| | | for (ScheduledFuture<?> future : futures) { |
| | | if (future != null && !future.isDone()) { |
| | | future.cancel(true); |
| | | } |
| | | } |
| | | } |
| | | log.debug("已停止任务 {} 的所有定时器", taskId); |
| | | } |
| | | taskScheduledTasks.clear(); |
| | | |
| | | // 关闭定时器线程池 |
| | | shutdownExecutor(scheduledExecutor, "定时器线程池"); |
| | | |
| | | // 关闭并行执行线程池 |
| | | shutdownExecutor(executorService, "并行执行线程池"); |
| | | |
| | | // 清空运行上下文 |
| | | runningTaskContexts.clear(); |
| | | |
| | | log.info("TaskExecutionEngine资源清理完成"); |
| | | } |
| | | |
| | | /** |
| | | * 关闭线程池 |
| | | */ |
| | | private void shutdownExecutor(ExecutorService executor, String name) { |
| | | if (executor == null || executor.isShutdown()) { |
| | | return; |
| | | } |
| | | |
| | | executor.shutdown(); |
| | | try { |
| | | if (!executor.awaitTermination(10, TimeUnit.SECONDS)) { |
| | | log.warn("{} 在10秒内未能正常关闭,强制关闭", name); |
| | | executor.shutdownNow(); |
| | | if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { |
| | | log.error("{} 强制关闭失败", name); |
| | | } |
| | | } else { |
| | | log.info("{} 已正常关闭", name); |
| | | } |
| | | } catch (InterruptedException e) { |
| | | log.warn("{} 关闭过程中被中断", name, e); |
| | | executor.shutdownNow(); |
| | | Thread.currentThread().interrupt(); |
| | | } |
| | | } |
| | | } |
| | | |