Search code examples
javaspringschedule

Run a job with (Spring @Scheduled) on specific days


I have a customer check job. I could not find how to automatically set the job time to run on 10am only on Monday, Friday and Saturday. Is there a possible way to set it using Spring @Scheduled?


Solution

  • I found the solution like this:

    @Scheduled(cron = "0 0 10 * * MON,FRI,SAT")
    public void dailyScheduleJob() {
        /*
        your code here
        */
    }
    

    Additionally, if the requested days are sequential such as Monday to Friday(a job running only on weekdays), this expression is shorter:

    @Scheduled(cron = "0 0 10 * * MON-FRI")
    public void dailyScheduleJob() {
        /*
        your code here
        */
    }
    

    It is also possible to represent days with numbers from 1-7. In this case 1 will be SUN, and 7 will be SAT and the same cron job above can be written like this:

    @Scheduled(cron = "0 0 10 * * 2-6")
    public void dailyScheduleJob() {
        /*
        your code here
        */
    }