Issue
I'm very new to cron
expression. I have only a basic understanding of how it works. I'm implementing an application that allows user to send in cron
expression value with pattern * * * * * *
. But the application will not allow cron
to run less than once every 30 minutes.
This is the validation method I wrote.
private boolean checkInvalidCronExpresstion(final String value){
final String[] expression = StringUtils.split( value, " " );
// not allow case "* * * * * *"
if (expression[0].equals( "*" )){
return true;
} else if ( expression[0].contains( "/" ) ){
final String[] minutes = StringUtils.split( expression[0], "/" );
diff = Integer.parseInt( minutes[1] );
// not allow case "*/x * * * * *" with x < 30
if (diff < 30 && expression[1].contains("*")){
return true;
}
}
return false;
}
My questions are:
- Does the method above cover all the invalid expression that will trigger
cron
less than every 30 minutes, and - I believe there could be a more elegant way to check the expression for example translate it into hours and minutes. I did look into Spring CronSequenceGenerator but I don't see it could help in this case.
Any utility class or solution recommended?
Solution
Don't reinvent the wheel here. Use a library such as cron-utils
to parse the Cron expression and validate it.
https://github.com/jmrozanec/cron-utils
Answered By - ck1