简体   繁体   English

在Spring Boot中执行计划的自定义SQL查询

[英]Execute Scheduled custom sql queries in Spring boot

I have a requirement to run custom queries at scheduled time. 我需要在计划的时间运行自定义查询。 Ex: User defines a custom query to run on postgres database at a particular time of the day. 例如:用户定义自定义查询,以便在一天的特定时间在postgres数据库上运行。 I need to implement a scheduler which picks up the custom queries and scheduled time which are stored in database and execute dynamically. 我需要实现一个调度程序,该调度程序可以接收存储在数据库中并动态执行的自定义查询和计划时间。

I can schedule the jobs using Cron scheduler using spring boot which defines the time and date as annotation. 我可以使用Spring引导程序使用Cron计划程序来计划作业,该程序将时间和日期定义为注释。 But I need to run multiple schedules my picking up date/time from db and run the custom query. 但是我需要运行多个时间表以从数据库中提取日期/时间并运行自定义查询。

public class SchedulingConfiguration implements SchedulingConfigurer {
   @Bean
   public TaskScheduler taskScheduler() {
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.setThreadNamePrefix("TaskScheduler");
    scheduler.setPoolSize(10);      
    scheduler.setWaitForTasksToCompleteOnShutdown(true);
    scheduler.setAwaitTerminationSeconds(20);
    return scheduler;
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    taskRegistrar.setScheduler(taskScheduler());
    taskRegistrar.addTriggerTask(new Runnable() {
        @Override
        public void run() {
                // Code which which should run at the specified executionTime( specified in nextExecutionTime(TriggerContext triggerContext))
        }
    }, new Trigger() {
        @Override
        public Date nextExecutionTime(TriggerContext triggerContext) {
            Calendar nextExecutionTime = new GregorianCalendar();
            Date lastActualExecutionTime = triggerContext.lastActualExecutionTime();
            nextExecutionTime.setTime(lastActualExecutionTime != null ? lastActualExecutionTime : new Date());
            nextExecutionTime.add(Calendar.MINUTE, 2); // runs every 2 minute and can also be read from database instead of hardcoding
            return nextExecutionTime.getTime();
        }
    });
}

} }

class Scheduler implements Runnable {
   public Scheduler(TaskScheduler scheduler, String timezone, String cron) {
      scheduler.schedule(this, new CronTrigger(cron, TimeZone.getTimeZone(timezone)));
   }

   @Override
   public void run() {
      //DO SOMETHING
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM