什么是在spring启动应用程序中安排任务的最佳方法

我目前正在开发基于Spring-Boot的应用程序。

我知道像@Scheduled这样的注释可以安排任务。 由于我的应用程序中的用户想要在不同的时间发送邮件并且只发送一次。

我已经阅读过Spring调度任务 – 只运行一次 ,但在基于Spring的应用程序中总是“新”一个localExecutor很奇怪。

这样,一旦用户安排发送电子邮件,我就必须为他的任务“新”一个localExecutor。

那么,还有更好的方法吗?

你应该使用quartz-schedulersend mails at different time and send only once. – 将此作为业务逻辑放在代码中。 请参阅spring boot -quartz integration https://github.com/davidkiss/spring-boot-quartz-demo

在Spring中安排任务的最简单方法是在Spring托管bean中创建由@Scheduled注释的方法。 它还需要@EnableScheduling类中的@EnableScheduling

春季教程

您可以在@Scheduled中使用crontab

  private AtomicInteger counter = new AtomicInteger(0); @Scheduled(cron = "*/2 * * * * *") public void cronJob() { int jobId = counter.incrementAndGet(); System.out.println("Job " + new Date() + ", jobId: " + jobId); }