11

I am new for scheduler in spring. I read so many articles on @schedule but in every example they gave time in seconds and milliseconds.

Problem Statement : As per my requirement, after my program start my scheduler will start after 15 minutes (initial Delay ) and then it executes the task every after 5 minutes (FixedRate) . To achieve this how can I give time in minutes is their any best way to achieve this problem ?

Code :

@Configuration
@EnableScheduling
public class ScheduledConfiguration {
    @Scheduled(fixedDelay = 300000, initialDelay = 900000)
    public void scheduleFixedRateWithInitialDelayTask() {

        long now = System.currentTimeMillis() / 1000;
        System.out.println("Fixed rate task with one second initial delay - " + now);
    }
}

By using above program i will achive but I want to avoid 300000 / 900000 milliseconds . Other way

@Scheduled(fixedDelay = 5 * 60 * 1000, initialDelay = 15 * 60 * 1000)

3 Answers 3

16

Although little bit late to the party, nevertheless another approach from Spring

@Scheduled(fixedDelayString = "PT15M", initialDelayString = "PT2H")

Here you can find the details about the syntax.

7

As per the JavaDocs:

The time unit is milliseconds by default but can be overridden via timeUnit.

So you can use java.util.concurrent.TimeUnit like this:

// ...
@Scheduled(fixedDelay = 5, initialDelay = 15, timeUnit = TimeUnit.MINUTES)
public void scheduleFixedRateWithInitialDelayTask() {
    // ...
}

This also works with fixedDelayString.

2

Well, both fixedDelay and initialDelay accepts values in milliseconds. So you can either go with:

@Scheduled(fixedDelay = 300000, initialDelay = 900000)

Or:

@Scheduled(fixedDelay = 5 * 60 * 1000, initialDelay = 15 * 60 * 1000)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.