Spring Boot 中的多线程 cron 作业



我正在开发一个Spring Boot应用程序,该应用程序在给定的网站中查找给定的keywords,如果找到匹配项,则废弃网页。我正在编写一个 cron 作业以每 5 分钟刷新一次结果,如下所示:

@Scheduled(cron = "* */5 * * * *")
public void fetchLatestResults() throws Exception {
LOG.debug("Fetching latest results >>>");
List<Keyword> keywords = keywordService.findOldestSearched10();
keywordService.updateLastSearchDate(keywords);
searchResultService.fetchLatestResults(keywords);
LOG.debug("<<< Latest results fetched");
}

数据库有 100 个keywords,在 cron 作业中,我首先列出上次获取结果的最旧的 10 个关键字。因此,例如,第一次运行应使用 ID 为 1 到 10 的keywords,第二次运行应使用 id 11 到 20,依此类推,第 11 次运行应再次使用 id 1 到 10,该过程将继续。

现在,问题是执行搜索的时间远远超过 5 分钟。因此,即使我将 cron 作业设置为每 5 分钟运行一次,在第一次运行完成之前不会进行第二次运行。因此,完成搜索需要几个小时。如何使此过程多线程,以便可以同时运行 cron 作业的多个实例,因为它们在不同的keywords列表上运行?

我建议你异步执行你的cron作业。

创建executor类,该类将创建一个新线程来运行您的 cron 作业:

@Component
public class YourCronJobExecutor {
private int threadsNumber = 10;
private ExecutorService executorService;
@PostConstruct
private void init() {
executorService = Executors.newFixedThreadPool(threadsNumber);
}
/**
* Start.
* @param runnable - runnable instance.
*/
public void start(Runnable runnable) {
try {
executorService.execute(runnable);
} catch (RejectedExecutionException e) {
init();
executorService.execute(runnable);
}
}
}

创建一个包含 cron 作业逻辑的processor类:

@Component
public class CronJobProcessor {
//logger
//autowired beans
public void executeYouCronJob() {
LOG.debug("Fetching latest results >>>");
List<Keyword> keywords = keywordService.findOldestSearched10();
keywordService.updateLastSearchDate(keywords);
searchResultService.fetchLatestResults(keywords);
LOG.debug("<<< Latest results fetched");
}
}

最后,您的 cron 作业类将如下所示:

@Component
public class YourCronJobClass {
private final YourCronJobExecutor yourCronJobExecutor;
private final CronJobProcessor cronJobProcessor;
@Autowired
public PopulateCourseStateController(YourCronJobExecutor yourCronJobExecutor,
CronJobProcessor cronJobProcessor) {
this.yourCronJobExecutor = yourCronJobExecutor;
this.cronJobProcessor = cronJobProcessor;
}   
@Scheduled(cron = "* */5 * * * *")
public void fetchLatestResults() throws Exception {
yourCronJobExecutor.start(cronJobProcessor::executeYouCronJob);
}
}

这样,执行 cron 作业将需要几毫秒,而实际执行作业的单独线程将根据需要运行。

但也许,您希望在单独的线程中执行每个关键字的搜索,但这是一个不同的故事。

最新更新