gpt4 book ai didi

java - Spring 中的任务调度

转载 作者:行者123 更新时间:2023-12-02 01:38:37 27 4
gpt4 key购买 nike

我们有一个要求,我们必须在数据库中收集 X 分钟的文档,其中 X 可以是 30-60。一旦这些文档被收集到数据库中,我们就必须通过 REST 调用将它们推送到单独的服务。

由于这些文档不会很大,我们将它们聚合在一起,然后将它们推送到一起。

现在,这些文档必须在固定的时间间隔后推送,所以我想到创建一个单独的线程,从数据库中提取记录,将它们推送到服务,一旦服务响应 200 OK,我就从数据库中删除这些记录数据库和线程进入 hibernate 状态 X 分钟。

class PushDocumentsToService extends Thread{
DocumentRepository documentRepository;
DocumentProcessingService documentProcessingService
public void run(){
List<Document> list = documentRepository.getAllDocuments();
Integer statusCode = documentProcessingService.sendDocuments(list);
if(statusCode == 200)
documentRepository.remove(list);
try{
Thread.sleep(30*60);
}catch(..){..}
}

}

现在,我的一些同事建议我不要在代码中使用 Thread.sleep。我无法理解的不良影响

Thread.sleep()

Spring Scheduler和Google Guava等库和框架使用什么方法来调度任务?

最佳答案

这里您需要做的就是使用 ScheduledExecutorService 来调度线程并提供适当的频率,如下所示。

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);    

Thread t1= new PushDocumentsToService();
scheduledThreadPool.scheduleAtFixedRate(t1, 0, 30,TimeUnit.SECONDS);

关于java - Spring 中的任务调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54821357/

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