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

Exi*_*xia 19 java spring spring-mvc

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

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

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

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

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

小智 25

在Spring中安排任务的最简单方法是创建@Scheduled在spring托管bean中注释的方法.它也适用@EnableScheduling于任何@Configuration类别.

春季教程

  • 当您在生产中拥有一项服务的多个实例时,这是否顺利? (2认同)

Sat*_* Kr 14

您可以在@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);
}
Run Code Online (Sandbox Code Playgroud)


小智 9

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