1

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. 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. But I need to run multiple schedules my picking up date/time from db and run the custom query.

Shiva
  • 31
  • 1
  • 6

2 Answers2

2
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();
        }
    });
}

}

Shiva
  • 31
  • 1
  • 6
0
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
   }
}
vimuth
  • 5,064
  • 33
  • 79
  • 116
PShetty
  • 545
  • 6
  • 14