本文主要是介绍动态控制定时任务增删启停,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.启动类增加注解
Application启动类上添加注解@EnableScheduling
2.创建 DynamicScheduledTaskRegistrar 核心类
@Slf4j
public class DynamicScheduledTaskRegistrar extends ScheduledTaskRegistrar {private final Map<String, ScheduledTask> scheduledTaskMap = new LinkedHashMap<>(16);public DynamicScheduledTaskRegistrar(){super();// 两种实现方案//ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);//TaskScheduler taskScheduler = new ConcurrentTaskScheduler(scheduledExecutorService);// 第二种实现方案ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();taskScheduler.setPoolSize(8);taskScheduler.setRemoveOnCancelPolicy(true);taskScheduler.setThreadNamePrefix("dynamic-scheduled-task-");taskScheduler.initialize();this.setScheduler(taskScheduler);}/*** 新增任务* @param taskName* @param cron* @param runnable*/public Boolean addCronTask(String taskName,String cron,Runnable runnable){if(scheduledTaskMap.containsKey(taskName)){log.error("定时任务["+ taskName+"]已存在,添加失败");return Boolean.FALSE;}CronTask cronTask = new CronTask(runnable,cron);ScheduledTask scheduledTask = this.scheduleCronTask(cronTask);scheduledTaskMap.put(taskName,scheduledTask);log.info("定时任务["+taskName+"]新增成功");return Boolean.TRUE;}/*** 删除任务* @param taskName*/public void cancelCronTask(String taskName){ScheduledTask scheduledTask = scheduledTaskMap.get(taskName);if(null != scheduledTask){scheduledTask.cancel();scheduledTaskMap.remove(taskName);}log.info("定时任务["+taskName+"]删除成功");}@Overridepublic void destroy() {super.destroy();scheduledTaskMap.values().forEach(ScheduledTask::cancel);}
}
测试请求
@Controller
@RequestMapping("/task/")
public class TaskController {@Resourcepublic DynamicScheduledTaskRegistrar dynamicScheduledTaskRegistrar;@RequestMapping("test")@ResponseBodypublic String testTask(){String cron ="0/5 * * * * ?";String taskName = "test";Runnable runnable = this::test;dynamicScheduledTaskRegistrar.addCronTask(taskName,cron,runnable);return "true";}public void test(){System.out.println("aaa");}
}
这篇关于动态控制定时任务增删启停的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!