Search code examples
springspring-bootcron

Run a job with Spring @Scheduled annotation at two different times on different days of the week


I have a job that has to be run

  • at 8:00 on weekdays
  • at 10:00 on weekends

My thinking is - Either

  • the CRON expression has to handle both of it together so that it can be given inside the @Scheduled annotation
  • Otherwise, a single @Scheduled annotation has to take in 2 CRON expression.

Is this possible?


Solution

  • @Schedules annotation can be used to set multiple calendar-based timer expressions.

    This annotation will get rid of the redundancy of writing the same method multiple times.

    In the following example, the first expression sets a timer to expire on the last day of every month. The second expression sets a timer to expire every Friday at 11:00 PM.

    @Schedules ({
        @Schedule(dayOfMonth="Last"),
        @Schedule(dayOfWeek="Fri", hour="23")
    })
    public void doPeriodicCleanup() { ... }