Sangam Belose
Sangam Belose

Reputation: 4506

Schedule Spring job so it should not run on 2nd and 4th saturday

I want to run my spring scheduled job on Week days and on Saturdays.( Saturday should not be the 2nd and 4th of month). Is there any way to achieve this using spring expressions.

public class PayoutJob {

@Scheduled(cron="0 0 11 1 * MON-FRI")
public void payout(){
    System.out.println("Started cron job");

    // some business logic
   }
}

The above job run on week days at 11 AM IST. Is there any way to calculate the the 2nd and 4th Saturday logic and put it in spring expression to avoid running the job on those days.

Upvotes: 1

Views: 258

Answers (1)

devops
devops

Reputation: 9197

My suggestion is, keep it short and simple:

public class PayoutJob {

    @Scheduled(cron="0 0 11 1 * MON-FRI")
    public void payoutMonFri(){
        doJob();
    }

    @Scheduled(cron="0 0 11 1 * SAT")
    public void payoutSat(){
        if(!is2ndOr4thSaturday()){
            doJob();
        }
    }

    void doJob(){
        System.out.println("Started cron job");
        // some business logic
    }

    boolean is2ndOr4thSaturday(){

        Calendar c = Calendar.getInstance();

        int dayOfWeek  = c.get(Calendar.DAY_OF_WEEK);
        if(dayOfWeek == Calendar.SATURDAY){
            int today = c.get(Calendar.DAY_OF_MONTH);
            c.set(Calendar.DAY_OF_MONTH, 1); // reset
            int saturdayNr = 0;

            while(c.get(Calendar.DAY_OF_MONTH) <= today){
                if(c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
                    ++saturdayNr;
                }
                c.add(Calendar.DAY_OF_MONTH, 1);
            }

            return saturdayNr == 2 || saturdayNr == 4;
        }

        return false;       
    }
}

I have corrected the while loop condition as per my requirement.

Upvotes: 1

Related Questions