Java 在 Spring Boot 应用程序中安排任务的最佳方法是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35064563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is best way to schedule task in spring boot application
提问by Exia
I am current developing an application based on Spring-Boot.
我目前正在开发基于 Spring-Boot 的应用程序。
I know that annotation like @Scheduled can schedule tasks. Since users in my application wanna send mails at different time and send only once.
我知道像@Scheduled 这样的注释可以调度任务。因为我的应用程序中的用户想要在不同的时间发送邮件并且只发送一次。
I have already read the post Spring scheduling task - run only once, but it is weird always "new" an localExecutor in a Spring based application.
我已经阅读了帖子Spring 调度任务 - 只运行一次,但是在基于 Spring 的应用程序中总是“新建”一个 localExecutor 是很奇怪的。
In that way , once a user schedule sending an email, I have to "new" an localExecutor for his task.
这样,一旦用户安排发送电子邮件,我必须为他的任务“新建”一个 localExecutor。
So , are there any better ways?
那么,有没有更好的办法呢?
采纳答案by Pankaj Pandey
you should use quartz-scheduler
and send mails at different time and send only once.
- put this as a business logic in your code.
Please see for spring boot -quartz integration
https://github.com/davidkiss/spring-boot-quartz-demo
你应该使用quartz-scheduler
和send mails at different time and send only once.
- 把它作为你代码中的业务逻辑。请参阅 spring boot -quartz 集成
https://github.com/davidkiss/spring-boot-quartz-demo
回答by Александр Косарев
The simplest way to schedule tasks in Spring is to create method annotated by @Scheduled
in spring managed bean. It also required @EnableScheduling
in any @Configuration
classes.
在 Spring 中调度任务的最简单方法是@Scheduled
在 spring 托管 bean 中创建注释的方法。它也是@EnableScheduling
任何@Configuration
课程所必需的。
回答by Satish Kr
You can use crontab inside @Scheduled
您可以在 @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);
}