SchedulingConfigurer is a simple SchedulingConfigurer and configureTasks method. The @enablesCheduling annotation must be added to the start class.
@Configuration @EnableScheduling @Slf4j public class RuleTask implements SchedulingConfigurer { private volatile ScheduledTaskRegistrar registrar; private ConcurrentHashMap<Long, ScheduledFuture<? >> scheduledFutures = new ConcurrentHashMap<>(); private ConcurrentHashMap<Long, CronTask> cronTasks = new ConcurrentHashMap<>(); @Override public void configureTasks(ScheduledTaskRegistrar registrar) { registrar.setScheduler(Executors.newScheduledThreadPool(30)); this.registrar = registrar; @param ruleList */ public void refresh(List<WarCron> cronList) {// Delete deleted tasks Set<Long> cronIds = scheduledFutures.keySet(); for (Long cronId : cronIds) { if (! exists(cronList, cronId)) { scheduledFutures.get(cronId).cancel(false); } } if (cronList ! = null) { for (WarCron warCron : cronList) { String expression = warCron.getCron(); / / timing task has been in existence and expression did not change to skip the if (scheduledFutures. Either containsKey (warCron. GetCronId () && cronTasks.get(warCron.getCronId()).getExpression().equals(expression)) { continue; } // If the execution time changes, Is to cancel the current timing task if (scheduledFutures. Either containsKey (warCron. GetCronId ())) { scheduledFutures.get(warCron.getCronId()).cancel(false); scheduledFutures.remove(warCron.getCronId()); cronTasks.remove(warCron.getCronId()); } CronTask task = new CronTask( new Runnable() { @Override public void run() { System. The out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- timing task -- -- -- -- -- -- -- -- -- -- -- -- -- -- "); } }, warCron.getCron() ); ScheduledFuture<? > future = registrar.getScheduler().schedule(task.getRunnable(), task.getTrigger()); cronTasks.put(warCron.getCronId(), task); scheduledFutures.put(warCron.getCronId(), future); @param cronId * @param cronId * @return */ private Boolean exists(List<WarCron>) warCronList, Long cronId) { for (WarCron warCron : warCronList) { if (cronId.equals(warCron.getCronId())) { return true; } } return false; }}Copy the code
Each time a new edit deletes a task in the database, the task must be refreshed to achieve the dynamic change of the task. When boot is started, the refresh method must be executed.
/** * @author: pandar * @date: 2021/3/120012 11:57 am * @description: */ @Component public class ApplicationRunnerConfig implements ApplicationRunner {@autoWired private RuleTask ruleTask; @Autowired private WarCronService warCronService; @Override public void run(ApplicationArguments args) throws Exception { List<WarCron> warCronList = warCronService.selectWarCronAll(); ruleTask.refresh(ruleList); }}Copy the code
Database table structure
cron_id | cron | delay |
---|---|---|
1 | 0/2 * * * *? | 0 |
2 | 0/7 * * * *? | 5 |