0

I can not find any cron expression that allows me to run batch job for last 3 Mondays of every month.

Lets say if current month has 4 weeks then I have to run the batch job for 2nd, 3rd and 4th Week of the month.

If Current month has 5 weeks then I have to run batch job for 3rd,4th & 5th Week.

As per my understanding I have to run my batch class for every monday(as there is no such cron expression for last 3 mondays)

But How can I filter it out so that batch class recognize the week and run only last 3 weeks?

1

All you need to check is add 21 days in today date.

so your code will be:-

DateTime today = System.now(); 
DateTime after21 = today.addDays(21); 
if(after21.month() != today.month()){    
    //run batch 
}

Lets say today is 10th sep and today is Monday. So when I add 21 days to day date next date will be 1st of oct. So this Monday is one of last 3 Mondays. I have added

"!=" and not ">"

in checking month condition because if you are checking for December month then adding 21 days will take you to next month which is January.

  • I have created below cron expression: String s= '0 0 10 ? * 2#3,4,5,2'; so if I run the job today then it will run the batch job on 17th Sept 2018 and then 24th. But September month does not have 5th Week so will it schedule at 8th Oct after 24th September and then continue? – Dhananjay Patil Sep 10 '18 at 15:29
  • I don't think above cron will work correctly. Above cron will only run on 3rd Monday of every month – Manjot Singh Sep 10 '18 at 19:20
  • 1
    you can test your cron on cronmaker.com – Manjot Singh Sep 10 '18 at 19:26
  • Checked the cron expression and it is showing incorrect results. I have put the condition mentioned by you in my Scheduler class and runs every monday. – Dhananjay Patil Sep 11 '18 at 7:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.