Setting up a Cron Job to Trigger on the Y-th Day Every Month, Handling Non-Existent Dates

24 Views Asked by At

I need assistance with configuring a recurring cron job to trigger an event on the Y-th day of every month. While I can use a straightforward expression like 0 0 10 * ? * to trigger the event on the 10th day of each month, there's a challenge with dates like the 31st, 30th, and 29th.

If I use 0 0 31 * ? *, events won't be triggered in months like April, June, September, and November where the 31st day doesn't exist. Similarly, using 0 0 30 * ? * won't work for February, and 0 0 29 * ? * won't work in non-leap years.

What I require is a solution where if the specified day doesn't exist in a particular month, the event triggers on the last day of that month instead. For instance, if I set the cron job to trigger on the 31st day and April doesn't have a 31st, I want the event to be triggered on the 30th of April.

While I understand that using 'L' in the cron expression can work for days like the 31st, it won't suffice for the 29th and 30th.

How can I modify my cron expression or implement a solution to achieve this functionality?

Current Cron Expression: 0 0 10 * ? * (For triggering the event on the 10th day of every month)

Desired Behavior: Trigger the event on the last day of the month if the specified day doesn't exist.

I appreciate any insights or solutions you can provide. Thank you!

1

There are 1 best solutions below

0
Sarthak Thakkar On

I have a solution to this problem. I'm not sure if it's the most optimal way, but it satisfies all the conditions.

If the date is 1-28(For eg. 10th)

  • cron(0 0 10 * ? *)

If the date is 31

  • cron(0 0 L * ? *)

If the date is 29 or 30, create two crons:

  • cron(0 0 29 1,3-12 ? *)
  • cron(0 0 L 2 ? *)