Cron expression must consist of 6 fields (found 1 in "#{systemEnvironment['db_cron']}")

18.9k views Asked by At

I'm trying to set a cron Scheduled annotation as follows:

@Scheduled(cron = "#{systemEnvironment['db_cron']}")
def void schedule() {

}

Next set the environment variable as:

export db_cron="0 19 21 * * *"

However, I get the runtime error:

Cron expression must consist of 6 fields 
  (found 1 in "#{systemEnvironment['db_cron']}")

What can be going wrong?


EDIT

I have also tried: @Scheduled(cron = "${db_cron}")

But this returns a compile time error:

/Users/snowch/repos/sales/Prospects/Snow/Plugwise/etl_service/src/main/groovy/com/ibm/etl/Application.groovy: 52: Expected '$db_cron' to be an inline constant of type java.lang.String in @org.springframework.scheduling.annotation.Scheduled
 @ line 52, column 23.
       @Scheduled(cron = "${db_cron}")
                         ^

/Users/snowch/repos/sales/Prospects/Snow/Plugwise/etl_service/src/main/groovy/com/ibm/etl/Application.groovy: -1: Attribute 'cron' should have type 'java.lang.String'; but found type 'java.lang.Object' in @org.springframework.scheduling.annotation.Scheduled
 @ line -1, column -1.
2 errors

:compileGroovy FAILED

FAILURE: Build failed with an exception.

I have tried @Scheduled(cron = "#{db_cron}")

But the runtime error was:

Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: static org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.setSystemPropertiesMode() is applicable for argument types: (java.lang.Integer) values: [2]
Possible solutions: setSystemPropertiesMode(int), setSystemPropertiesModeName(java.lang.String)
    at groovy.lang.MetaClassImpl.invokeStaticMissingMethod(MetaClassImpl.java:1373)
    at groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1359)
    at org.codehaus.groovy.runtime.callsite.StaticMetaClassSite.call(StaticMetaClassSite.java:50)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at com.ibm.etl.Application.main(Application.groovy:43)

Note the environment variable is set as follows:

snowch$ echo "$db_cron"
0 19 21 * * *
2

There are 2 answers

8
Nikolay Rusev On BEST ANSWER

You should set env variable like you do:

export db_cron="0 19 21 * * *"

then restart your ide if you are using or restart your terminal session.

@Scheduled(cron = "${db_cron}")
def void schedule() {
   ...
}

I tried it and here is my screenshot. Everything works as expected...cron expression as env variable

0
Emerson Vicente On

For me worked using JDK 11 and Spring 2.3.3 adding double quotes both the variables:

export db_cron="0 19 21 * * *"

and:

@Scheduled(cron = "${db_cron}")

Note: works in application.properties files too.