目录
- 定时任务管理器
- 定时任务的任务接口
- 定时任务和定时任务结果的缓存对象
- 定时任务
- 使用姿势
定时任务管理器
- 负责启动一个定时任务、停止一个定时任务、更新一个定时任务
public class ScheduleManager {private final Logger logger = LoggerFactory.getLogger(ScheduleManager.class);@Autowiredprivate ThreadPoolTaskScheduler taskScheduler;private final Map<String, ScheduleTaskHolder> cache = new ConcurrentHashMap<>();public ScheduleManager(ThreadPoolTaskScheduler taskScheduler) {this.taskScheduler = taskScheduler;}public String startTask(ScheduleTask scheduleTask, String cron) {ScheduledFuture<?> scheduledFuture = taskScheduler.schedule(scheduleTask, new CronTrigger(cron));String key = UUID.randomUUID().toString();ScheduleTaskHolder holder = new ScheduleTaskHolder(scheduleTask, scheduledFuture);cache.put(key, holder);logger.info("{} 定时任务启动成功!唯一标识为:{}", scheduleTask.getName(), key);return key;}public void stopTask(String key) {if (StringUtils.isBlank(key)) {return;}ScheduleTaskHolder holder = cache.get(key);if (Objects.isNull(holder)) {return;}ScheduledFuture scheduledFuture = holder.getScheduledFuture();boolean cancel = scheduledFuture.cancel(true);if (cancel) {logger.info("{} 定时任务停止成功!唯一标识为:{}", holder.getScheduleTask().getName(), key);} else {logger.error("{} 定时任务停止失败!唯一标识为:{}", holder.getScheduleTask().getName(), key);}}public String changeTask(String key, String cron) {if (StringUtils.isAnyBlank(key, cron)) {throw new RuntimeException("定时任务的唯一标识以及新的执行表达式不能为空");}ScheduleTaskHolder holder = cache.get(key);if (Objects.isNull(holder)) {throw new RuntimeException(key + "唯一标识不存在");}stopTask(key);return startTask(holder.getScheduleTask(), cron);}}
定时任务的任务接口
public interface ScheduleTask extends Runnable {String getName();}
定时任务和定时任务结果的缓存对象
public class ScheduleTaskHolder implements Serializable {private ScheduleTask scheduleTask;private ScheduledFuture scheduledFuture;public ScheduleTaskHolder() {}public ScheduleTaskHolder(ScheduleTask scheduleTask, ScheduledFuture scheduledFuture) {this.scheduleTask = scheduleTask;this.scheduledFuture = scheduledFuture;}public ScheduleTask getScheduleTask() {return scheduleTask;}public void setScheduleTask(ScheduleTask scheduleTask) {this.scheduleTask = scheduleTask;}public ScheduledFuture getScheduledFuture() {return scheduledFuture;}public void setScheduledFuture(ScheduledFuture scheduledFuture) {this.scheduledFuture = scheduledFuture;}
}
定时任务
public class ThreadPoolWarnTask implements ScheduleTask {@Overridepublic String getName() {return "threadPoolWarnTask";}@Overridepublic void run() {}
}
使用姿势
- 引入 ScheduleManager 对象
- 开启定时任务、关闭定时任务、更新定时任务
String taskKey = scheduleManager.startTask(threadPoolWarnTask, CRON);
scheduleManager.stopTask(taskKey);
scheduleManager.changeTask(taskKey, newCRON);