Spring MVC:如何在一天的特定时间安排工作。每天安排的时间都不一样。这些作业需要运行的时间在数据库表中可用。我能够从表中读取数据,但不确定如何在spring mvc中调度它们。谁来帮帮忙?
Spring调度器要求您在编译时知道一天中的时间,所以这会变得有点奇怪。但是,如果您想要更有创意,您可以在午夜安排一个作业,以查询数据库中任务应该运行的确切时间,在该时间之前休眠,然后执行任务。像这样:
public abstract class DailyTaskRunner {
// Execute the specific task here
protected abstract void executeTask();
// Query the database here
// Return the number of milliseconds from midnight til the task should start
protected abstract long getMillisTilTaskStart();
// Run at midnight every day
@Scheduled(cron="0 0 * * *")
public void scheduledTask() {
long sleepMillis = getMillisTilTaskStart();
try {
Thread.sleep(sleepMillis);
} catch(InterruptedException ex) {
// Handle error
}
executeTask();
}
}
您可以为每个作业扩展该类一次。