3

I was trying to define the cron details in my spring @Scheduled method

@Service
@PropertySource("classpath:application.properties")
public class CacheRefreshService {

@Scheduled(cron = "${api.refresh.cron}")
     public void refreshJob() throws Exception {
        LOGGER.info("Started Refresh");
        //do something
     }
}

And in my application.properties

#Refresh
api.refresh.cron =0 29 11 * * ?

When I define the cron details along with @Scheduled, it is running fine. But when I do this, it is not able to read the value from the properties file and the below error is thrown.

Caused by: java.lang.IllegalStateException: Encountered invalid @Scheduled method 'refreshJob': Cron expression must consist of 6 fields (found 1 in "${api.refresh.cron}")

Any suggestions please?

Chillax
  • 4,418
  • 21
  • 56
  • 91
  • Your `@PropertySource` should go on an `@Configuration` class not a `@Service` class. Also your code doesn't seem to match the error you get, so which is it... – M. Deinum Dec 10 '15 at 08:10
  • @M.Deinum This is a service class. So how do I read the property here? Have updated the error message – Chillax Dec 10 '15 at 08:43
  • 2
    The use of the property (`@Value`) is something different then reading the file. Your `@PropertySource` is now pretty much useless as it doesn't do anything. Also you need to register a `PropertySourcesPlaceholderConfigurer` to have things replaced. – M. Deinum Dec 10 '15 at 09:01
  • @M.Deinum It worked. Thanks – Chillax Dec 10 '15 at 10:01

2 Answers2

2

Adding the below to my ApplicationContext resolved the issue..

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
       return new PropertySourcesPlaceholderConfigurer();
    }
Chillax
  • 4,418
  • 21
  • 56
  • 91
1
factoryBean.setCronExpression("0 0/1 * 1/1 * ? *"); 

you have to set Cron Expresssion bcz in BeanFactory Class the setCronExpression is mandatory

Dherik
  • 17,757
  • 11
  • 115
  • 164
Purushottam
  • 149
  • 4
  • 17