Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best way to schedule task in spring boot application

I am current developing an application based on 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.

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.

In that way , once a user schedule sending an email, I have to "new" an localExecutor for his task.

So , are there any better ways?

like image 971
Exia Avatar asked Jan 28 '16 14:01

Exia


People also ask

How do I schedule a task in spring boot?

Java Cron ExpressionThe @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file. The @Scheduled annotation is used to trigger the scheduler for a specific time period.


4 Answers

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 tutorial

like image 149
Александр Косарев Avatar answered Oct 10 '22 18:10

Александр Косарев


You can use crontab inside @Scheduled

 private AtomicInteger counter = new AtomicInteger(0);

@Scheduled(cron = "*/2 * * * * *")
public void cronJob() {
    int jobId = counter.incrementAndGet();
    System.out.println("Job " + new Date() + ", jobId: " + jobId);
}
like image 14
Satish Kr Avatar answered Oct 10 '22 19:10

Satish Kr


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

like image 9
Pankaj Pandey Avatar answered Oct 10 '22 17:10

Pankaj Pandey


Spring @Scheduled annotation will execute multiple times if you have more than one instance of your app where you have @Scheduled annotation.

If you are using PCF, you can use PCF scheduler https://docs.pivotal.io/scheduler/1-2/using-jobs.html to avoid this issue. Using Tasks can solve this issue.

like image 1
Ketan Avatar answered Oct 10 '22 18:10

Ketan