Java 在Spring boot中执行计划的自定义sql查询
我需要在预定时间运行自定义查询。 例如:用户定义一个自定义查询,在一天中的特定时间在postgres数据库上运行。我需要实现一个调度器,该调度器拾取存储在数据库中的自定义查询和计划时间,并动态执行 我可以使用Cron调度器和springboot来调度作业,springboot将时间和日期定义为注释。但是我需要运行多个计划,从数据库中选择日期/时间,并运行自定义查询Java 在Spring boot中执行计划的自定义sql查询,java,spring,Java,Spring,我需要在预定时间运行自定义查询。 例如:用户定义一个自定义查询,在一天中的特定时间在postgres数据库上运行。我需要实现一个调度器,该调度器拾取存储在数据库中的自定义查询和计划时间,并动态执行 我可以使用Cron调度器和springboot来调度作业,springboot将时间和日期定义为注释。但是我需要运行多个计划,从数据库中选择日期/时间,并运行自定义查询 class Scheduler implements Runnable { public Scheduler(TaskSche
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
}
}
}您能告诉我们何时更新数据库中的下一个schdeule时间吗?计划一旦创建,应每天在指定的时间运行,或定期在指定的时间间隔运行(如cron表达式),然后@scheduler将为您工作。我认为你必须在数据库上节省时间是的。它应该在数据库上节省的时间上运行。。我的意思是,时间就像一个cron表达式……(每天、每个星期等)。这可能会给我们一些启示:如果cron表达式不动态更改,这是有效的。我找到了上面的解决方案,我们可以用它动态地安排任务。
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();
}
});
}