gpt4 book ai didi

java - 调度 : execute tasks only one time in spring boot

转载 作者:搜寻专家 更新时间:2023-11-01 03:00:05 24 4
gpt4 key购买 nike

我正在尝试使用 spring boot 管理计划任务。我想在特定日期只执行一次(由用户指定)。用户可以根据需要添加执行日期。这是我的工作:

@Component
public class JobScheduler{

@Autowired
ServiceLayer service;

@PostConstruct
public void executeJob(){
try {
service.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

这是执行方法:

private TaskScheduler scheduler;

Runnable exampleRunnable = new Runnable(){
@Override
public void run() {
System.out.println("do something ...");
}
};

@Override
@Async
public void execute() throws Exception {
try {

List<Date> myListOfDates = getExecutionTime(); // call dao to get dates insered by the user

ScheduledExecutorService localExecutor = Executors.newSingleThreadScheduledExecutor();
scheduler = new ConcurrentTaskScheduler(localExecutor);
for(Date d : myListOfDates ){
scheduler.schedule(exampleRunnable, d);
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

问题 1:我正在使用 PostConstruct 注释。因此,当调用 executeJob 方法时,列表“myListOfDates”中没有日期。

问题 2:假设 myListOfDates 包含日期,如果用户输入另一个日期,我如何获取最新日期?

问题 3:如果我使用 @Scheduled(initailDelay=10000, fixedRate=20000) 而不是 @PostConstruct 注释,它将解决第一个问题,但它会每 20 秒执行一次作业。

有什么线索吗?

最佳答案

从您的问题中我可以推断,您是在询问如何根据 Spring 开始的日期列表来触发作业。

首先,而不是使用@PostConstruct在 bean/组件中,我认为最好将它挂接到应用程序级事件监听器中。参见 http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/event/ContextRefreshedEvent.html

这样,您可以确保所有 bean 都已初始化,因此您可以加载 myListOfDates ,然后启动调度程序。

其次,就像我在评论中所说的那样,我建议您改用现有的第 3 方库。我只在 Java 中使用过 Quartz,所以我将说明如何使用 Quartz。

第三,我猜你正在存储myListOfDates在某种数据库(不是内存)中,因此用户可以修改预定日期。如果您按照我的建议使用 3rd-party 库,Quartz 有使用 JDBC 的 JobStore 参见 http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/tutorial-lesson-09.html#TutorialLesson9-JDBCJobStore

老实说我从来没有用过那个,但我相信图书馆有机制根据数据库中保存的内容触发作业。这可能就是您正在寻找的。

关于java - 调度 : execute tasks only one time in spring boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37511097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com