How to read value in integer in @Schedule annotation?

Viewed 118

The variable used in @Schedule is defined in some other project but to use it in another project it is read in a class and the passed in @Scheduled in other file.

The variable is defined in the class as:

@Value("${cron_frequency_interval_for_logs}")
int cronFrequencyIntervalForLogs;

and used as

@Scheduled(fixedDelayString = "${cron_frequency_interval_for_logs}")

This works fine but the time it takes is in milliseconds and that too in String type.

What I want and tried is: want the time in integer form and in minutes:

@Value("${cron_frequency_interval_for_logs}")
int cronFrequencyIntervalForLogs;

This syntax I copied from internet but didn't work for me.

@Scheduled(fixedDelay = "#{new Integer('${cron_frequency_interval_for_logs}')}")

I want the time to be in minutes as first priority but by referring to the below article I got to know the format would be 5*60*1000 for 5 minutes and in such a case if I can just store 5 in the variable and can do the rest of the calculation as that is going to be repetitive.

Is there any way of doing this? Referred this

1 Answers

Let's say you have a property (not a variable) called run-frequency.minutes which contains an integer of how frequently you would like a method to execute. There are three annotation properties that will come in handy:

  • initialDelayString - Value of how long to wait before the first execution.
  • fixedDelayString - Value of how long to wait between executions.
  • timeUnit - The unit to use when evaluating the above two values (MINUTES, SECONDS, etc).
@Scheduled(
    initialDelayString = "${run-frequency.minutes}",
    fixedDelayString = "${run-frequency.minutes}",
    timeUnit = TimeUnit.MINUTES
)

On a side note, here is the JavaDoc for that annotation: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/Scheduled.html

Related