Noam Noam - 1 year ago 445
Java Question

How to use @Scheduled(cron) with SpEL in spring?

I have a method that I want spring to schedule - for that matter I'm using the

annotation - and to be more exact, I'm using a cron expression.
My cron expression is in a property file that is called
When I'm using it as a placeholder
- everything works great; but I want to use SpEL (
) , and it does't work - throws the following exception:
java.lang.IllegalArgumentException: cron expression must consist of 6 fields (found 1 in #{scheduler['cron']})

What am I doing wrong here?

Here is my cron expression from the properties file:
cron=0 0/1 * * * ?

Here is the stack trace that I get:
java.lang.IllegalArgumentException: cron expression must consist of 6 fields (found 1 in #{scheduler['cron']})
at org.springframework.scheduling.config.ScheduledTaskRegistrar.afterPropertiesSet(
at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.onApplicationEvent(
at org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor.onApplicationEvent(
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(
at org.springframework.web.context.ContextLoader.initWebApplicationContext(
at org.springframework.web.context.ContextLoaderListener.contextInitialized(
at org.apache.catalina.core.StandardContext.listenerStart(
at org.apache.catalina.core.StandardContext$
at org.apache.catalina.core.StandardContext$
at java.util.concurrent.FutureTask$Sync.innerRun(
at java.util.concurrent.ThreadPoolExecutor.runWorker(
at java.util.concurrent.ThreadPoolExecutor$

It seems that spring is trying to parse the following string as the cron experssion "#{scheduler['cron']}" insraed of the actual cron expression itself.

Answer Source

According to the error message, the value of the cron expression in your properties file is incorrect.

It does not conform to the expected syntax.

The value should contain six fields and look something like this.

* 10 * * * *

Here's the code that throws this exception

 * Parse the given pattern expression.
private void parse(String expression) throws IllegalArgumentException {
    String[] fields = StringUtils.tokenizeToStringArray(expression, " ");
    if (fields.length != 6) {
        throw new IllegalArgumentException(String.format(""
                + "cron expression must consist of 6 fields (found %d in %s)", fields.length, expression));

It may not be possible to externalize cron configuration using spEL in an Annotation.

The alternatives are to use XML or use the cron expression.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download