spring引导调度

0kjbasz6  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(214)

朋友们,我有一个要求,客户可以安排一个工作每周,他可以随时更改此值,而无需重新启动应用程序它应该有新的变化适用。应用程序将被许多客户机使用,因此将有多个动态调度程序,每个都将根据其配置运行。示例-

Customer1 schedules Job on Monday 1:00PM 
Customer2 schedules Job on Wednesday 3:00AM

我需要编写sprint引导调度器,它可以动态地从数据库中获取这些值。假设这个开始正常运行,customer1将作业计时更改为

Customer1 reschedules Job on Friday 1:00PM

那么应用程序应该有这些更改。我能够从数据库中获得价值,并能够动态地运行它。但是,当客户更改值时,如何在不重新启动应用程序的情况下重新触发作业。我已经通过几个环节,但需要一个可行的解决方案,因为我不明白。
我所做的

@SpringBootApplication
@EnableScheduling
@EnableAsync
@EnableConfigurationProperties
public class PricingApplication extends SpringBootServletInitializer implements SchedulingConfigurer, DisposableBean {

    ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    public static void main(String[] args) {
        SpringApplication.run(PricingApplication.class, args);
    }

    public Map<Long, String> myCustomScheduler(){
     // Hard coded below values but actually it will populate from DB and cron expression will get as below
        Map<Long, String> cronSchedule = new HashMap<>();
        cronSchedule.put(1L, "*/25 * * * * *");
        cronSchedule.put(2L, "*/5 * * * * *");
        return cronSchedule;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar){
        Map<Long, String> cronValues =  myCustomScheduler();

        cronValues.forEach((customer, cronValue) ->{
            Runnable runTask = () -> System.out.println("This is the task scheduled for customer - "+customer+ "  Ans cron Expression is "+cronValue);
            Trigger trigger = new Trigger() {
                @Override
                public Date nextExecutionTime(TriggerContext triggerContext) {
                    Map<Long, String> newCronValues = myCustomScheduler();
                    String newCron = newCronValues.get(customer);
                    if(!newCron.equalsIgnoreCase(cronValue)){
                        taskRegistrar.setTriggerTasksList(new ArrayList<TriggerTask>());
                        configureTasks(taskRegistrar);
                        taskRegistrar.destroy();
                        taskRegistrar.setScheduler(scheduledExecutorService);
                        taskRegistrar.afterPropertiesSet();
                        return  null;
                    }
                    CronTrigger cronTrigger = new CronTrigger(cronValue);
                    return cronTrigger.nextExecutionTime(triggerContext);
                }
            };
            taskRegistrar.addTriggerTask(runTask, trigger);
        });
    }

    @Override
    public void destroy() throws Exception {
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdownNow();
        }
    }
}

处理上述情况的任何建议或最佳方法。感谢您的回复

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题