diff --git a/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java b/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java index 08a6444a6b..120ced6132 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java +++ b/spring-context/src/main/java/org/springframework/scheduling/support/CronExpression.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2020 the original author or authors. + * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -202,6 +202,25 @@ public final class CronExpression { } } + /** + * Determine whether the given string represents a valid cron expression. + * @param expression the expression to evaluate + * @return {@code true} if the given expression is a valid cron expression + * @since 5.3.8 + */ + public static boolean isValidExpression(@Nullable String expression) { + if (expression == null) { + return false; + } + try { + parse(expression); + return true; + } + catch (IllegalArgumentException ex) { + return false; + } + } + private static String resolveMacros(String expression) { expression = expression.trim(); diff --git a/spring-context/src/test/java/org/springframework/scheduling/support/CronExpressionTests.java b/spring-context/src/test/java/org/springframework/scheduling/support/CronExpressionTests.java index 23319d5ca9..104e482828 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/support/CronExpressionTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/support/CronExpressionTests.java @@ -51,6 +51,16 @@ class CronExpressionTests { } }; + @Test + public void isValidExpression() { + assertThat(CronExpression.isValidExpression(null)).isFalse(); + assertThat(CronExpression.isValidExpression("")).isFalse(); + assertThat(CronExpression.isValidExpression("*")).isFalse(); + assertThat(CronExpression.isValidExpression("* * * * *")).isFalse(); + assertThat(CronExpression.isValidExpression("* * * * * * *")).isFalse(); + + assertThat(CronExpression.isValidExpression("* * * * * *")).isTrue(); + } @Test void matchAll() {