53

I am trying to schedule a task in Spring which is to be run everyday at midnight. I followed the official guide from Spring and made the scheduler class as below:

@Component
public class OverduePaymentScheduler {    
    @Scheduled(cron = "0 0 0 * * *")
    public void trackOverduePayments() {
        System.out.println("Scheduled task running");
    }
}

However the task does not run when the clock hits 12am. I got the cron expression from the documentation for quartz scheduler at this link.

The scheduler is executed fine if I change the cron expression to "*/10 * * * * *" which runs every ten seconds.

So what am I doing wrong?

madx
  • 6,723
  • 4
  • 55
  • 59
Charlie
  • 3,113
  • 3
  • 38
  • 60
  • 2
    if you are on spring 5.3.3 or above, try @Scheduled(cron = "@midnight"). Cron expressions can be hard to read for a human eye. ref: https://spring.io/blog/2020/11/10/new-in-spring-5-3-improved-cron-expressions – Anshul Jun 21 '21 at 03:55

5 Answers5

120

These are valid formats for cron expressions:

  • 0 0 * * * * = the top of every hour of every day.
  • */10 * * * * * = every ten seconds.
  • 0 0 8-10 * * * = 8, 9 and 10 o'clock of every day.
  • 0 0 6,19 * * * = 6:00 AM and 7:00 PM every day.
  • 0 0/30 8-10 * * * = 8:00, 8:30, 9:00, 9:30, 10:00 and 10:30 every day.
  • 0 0 9-17 * * MON-FRI = on the hour nine-to-five weekdays
  • 0 0 0 25 12 ? = every Christmas Day at midnight

The pattern is:

second, minute, hour, day, month, weekday

So your answer is:

0 0 0 * * *
RazvanParautiu
  • 2,805
  • 2
  • 18
  • 21
44

I finally got it to work with this cron expression 0 0 0 * * * but I had to set the time zone in the scheduler class like this. @Scheduled(cron = "0 0 0 * * *",zone = "Indian/Maldives")

Charlie
  • 3,113
  • 3
  • 38
  • 60
20

Please use below cron pattern for 12:00 AM every day:

    // at 12:00 AM every day
    @Scheduled(cron="0 0 0 * * ?")

I have checked your cron pattern at this website:http://www.cronmaker.com/.

It says pattern 0 0 0 * * * as invalid.

Ajit Soman
  • 3,926
  • 3
  • 22
  • 41
5

For spring 5.3 or above users, we have a much simpler way to define crons

Macro Meaning
@yearly (or @annually) once a year (0 0 0 1 1 *)
@monthly once a month (0 0 0 1 * *)
@weekly once a week (0 0 0 * * 0)
@daily (or @midnight) once a day (0 0 0 * * *)
@hourly once an hour, (0 0 * * * *)

ref: https://spring.io/blog/2020/11/10/new-in-spring-5-3-improved-cron-expressions

Anshul
  • 159
  • 1
  • 10
3

You can use below format to satisfy your requirement:

0 0 23 * * *

Since the hours starts from 0 to 23 for Quartz configuration. You can refer this link for more information.

RahuL Sharma
  • 478
  • 4
  • 8