0

I want to read fixedDelay from a property file so doing below.

@Bean
public Runnable method(){  
static final int delay= properties.getConnectionConfig().getConnectMonitorDelay();
        return new Runnable() {
            @Override
            @Scheduled(fixedDelay = delay)
            public void run() {}
       };
}

properties.getConnectionConfig().getConnectMonitorDelay() already return a primitive int but i am getting below compile error.

The value for annotation attribute Scheduled.fixedDelay must be a constant expression

How to get rid of the compile error?

Harshana
  • 7,297
  • 25
  • 99
  • 173

1 Answers1

0

Java annotations take compile time constants, which are defined as final primitives or strings.

In Spring Boot, you can use an application property directly with fixedDelayString, fixedRateString, initialDelayString properties.

@Bean
public Runnable method(){
    return new Runnable() {
        @Override
        @Scheduled(fixedDelayString = "${connection-config.connect-monitor-delay}")
        public void run() {
            // ..
        }
    };
}

Check out this link for more different approaches:

Scheduling a job with Spring programmatically (with fixedRate set dynamically)

İsmail Y.
  • 3,579
  • 5
  • 21
  • 29
  • Java annotations take compile time constants, which are defined as final primitives -> why would code i asked giving compile error then – Harshana May 28 '22 at 13:06
  • I may not be able to focus, because when you run your code first; don't you get *`illegal start of expression`* error because you are declaring static local variable in method? – İsmail Y. May 28 '22 at 14:47