线程池管理定时调度

avatar
作者
猴君
阅读量:0
/**  * 调度管理器  *  * @author QiJingJing  */ @Service public class SchedulerService {     private static final Logger logger = LoggerFactory.getLogger(SchedulerService.class);     private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);     private final ConcurrentHashMap<String, ScheduledFuture<?>> tasks = new ConcurrentHashMap<>();      public void scheduleTask(String taskId, Runnable task, Date executionTime) {         // Cancel existing task if it exists         cancelTask(taskId);         long delay = executionTime.getTime() - System.currentTimeMillis();         if (delay > 0) {             ScheduledFuture<?> future = scheduler.schedule(task, delay, TimeUnit.MILLISECONDS);             tasks.put(taskId, future);             logger.warn("Adding a task succeeded");         } else {             logger.warn("Time is less than the current time");         }     }      public void cancelTask(String taskId) {         ScheduledFuture<?> future = tasks.remove(taskId);         if (future != null) {             // Cancel the scheduled task without interrupting it             future.cancel(false);             logger.warn("Cancel successfully");         }     }      public void shutdown() {         scheduler.shutdown();     } } 
@Service public class TaskService {          @Autowired     private SchedulerService schedulerService;      public void addOrUpdateTask(String taskId, Runnable runnable, Date executionTime) {         schedulerService.scheduleTask(taskId, runnable, executionTime);     }      public void removeTask(String taskId) {         schedulerService.cancelTask(taskId);     }      public void shutdown() {         schedulerService.shutdown();     } }

在需要引入的核心逻辑中,进行添加调度,taskId为标识,支持取消调度。传入调度执行方法即可

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!