20

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?

Community
  • 1
  • 1
Exia
  • 2,111
  • 3
  • 15
  • 24
  • For more dynamic use cases checkout https://stackoverflow.com/questions/46974272/spring-boot-add-new-schedule-job-dynamically – RoBeaToZ Feb 12 '20 at 10:32

4 Answers4

25

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

  • 1
    yes , I have already use this kind of annotations for scheduling task. But in my condition , a user only want to send his mail once at a given time. So if I use the @Schedule annotation , I have to “polling” check whether an mail should be send each several minutes or hours..... – Exia Jan 28 '16 at 15:01
  • Hope [this](http://stackoverflow.com/questions/17402112/correct-way-to-persist-quartz-triggers-in-database) can be helpful for you – Александр Косарев Jan 28 '16 at 15:19
  • 2
    Does this works smooth when you have multiple instances of one service in production? – virsha Aug 26 '18 at 11:03
  • Checkout use of [shedlock](https://www.baeldung.com/shedlock-spring) with spring for making this work better in clustered environments (multiple instances) – solecoder Dec 08 '20 at 12:40
14

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);
}
Satish Kr
  • 590
  • 5
  • 12
9

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

Pankaj Pandey
  • 1,007
  • 6
  • 10
1

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.

Ketan
  • 2,082
  • 5
  • 28
  • 44