4

I am using Spring scheduler as given bellow.

 @Scheduled(fixedDelay = ((10 * 60 * 1000) / 2))
    public void runDynamic()
    {
      //doing my stuff
    }

Now suppose I have one constant like this

public static final Integer VARIANCE_TIME_IN_MIN = 10;

And I want to use this constant as a part of my expression something like this :

@Scheduled(fixedDelay = ((MyConstants.VARIANCE_TIME_IN_MIN * 60 * 1000) / 2))
public void runDynamic()
{
//doing my stuff
}

but it is giving my compile time error. Any ideas? Thanks in Advance..!

Vishal Zanzrukia
  • 4,902
  • 4
  • 38
  • 82

3 Answers3

7

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

SO change your definition to

   public static final int VARIANCE_TIME = 10;
   public static final long FIXED_DELAY = ((VARIANCE_TIME * 60 * 1000) / 2)

   @Scheduled(fixedDelay = FIXED_DELAY)
   public void runDynamic()      
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
0

Use Task scheduling using cron expression from properties file

@Scheduled(cron = "${cronTrigger.expression}")
public void runDynamic()
    {
      //doing my stuff
    }

Config in XML File:

<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
    <property name="jobDetail" ref="exampleJob" />
    <!-- run every morning at 6 AM -->
    <property name="expression" value="0 0 6 * * ?" />
</bean>

This link1 and doc might help you

You can also create the Tash Scheduler dynamically(programatically) as explained here

Community
  • 1
  • 1
Jeba Prince
  • 1,669
  • 4
  • 22
  • 41
0
private static final long VARIANCE_TIME_IN_MIN = 10l;

@Scheduled(fixedDelay = ((VARIANCE_TIME_IN_MIN * 60 * 1000) / 2))
public void runDynamic() {
    // ...
}
visionken
  • 65
  • 1
  • 7
  • 1
    could've also explained that you changed the type to long, as it's not easily visible – Alex Savitsky Jan 19 '18 at 16:15
  • 2
    While this code may answer the question, providing additional context regarding **how** and **why** it solves the problem would improve the answer's long-term value. – Alexander Jan 19 '18 at 16:55