1

I have some question related to the @Scheduled task in spring boot application

I have some microservice that send an email every month. I have @Scheduled(cron="every month expression"). But just imagine that I have run this service for 15 days (but we need 30 days to send email) and on 16-day service restarted or crashed and after some time wake up again. This job will start count 1 month again with the first day or continue with 16 and so on days?

@Scheduled(cron="0 0 0 1 * *")
public void sendEmail() {
    emailService.sendEmail();
}

I need that after the server crashes, let's say for 15 days this task continues from 15 days and after 15 days sent a letter, but did not start counting again from the first day

  • You should use a different scheduler for that. It could be a Jenkins job or something else that you can monitor. Also, I guess you want to send one email every month, but the @Scheduled annotation will send N emails because you deployed N instances of your microservice. Otherwise, schedule your task at a different rate (e.g. every minute) and manage action execution via a database. – Jonathan Lermitage Jul 28 '19 at 13:00
  • You can also use a service that will send emails. Your microservice sends an event like "send email template X with data Y at date Z", and your emailing service will handle that. – Jonathan Lermitage Jul 28 '19 at 13:05

2 Answers2

0

Use this cron :

0 0 0 1 * ?

This will run the scheduler 1st day of every month regardless of when server get started.

Avinash Gupta
  • 208
  • 5
  • 18
0

cron expression is designed to run a job on everyday or specific day of month or week, and i think your understanding is wrong. Your corn expression for specific day but no for period tracking, online corn use that online generator for more information

0 0 0 1 * ? *

The above expression is designed to run At 00:00:00am, on the 1st day, every month

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98