Spring's @Scheduled annotation's fixedDelay property can be used to execute the annotated method with a fixed period between the end of the last invocation and the start of the next.
Example
Using @Scheduled annotation with fixedDelay
In this example we are creating two @Scheduled methods, one with fixedDelay and other with fixedDelayString
package com.logicbig.example;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalTime;
@Component
public class MyBean {
@Scheduled(initialDelay = 1000, fixedDelay = 1000)
public void runTask() {
System.out.printf("Running scheduled task " +
" thread: %s, time: %s%n",
Thread.currentThread().getName(),
LocalTime.now());
}
@Scheduled(initialDelay = 1000,
fixedDelayString = "2000")
public void runTask2() {
System.out.printf("Running scheduled task 2" +
" thread: %s, time: %s%n",
Thread.currentThread().getName(),
LocalTime.now());
}
}
Main class
package com.logicbig.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@ComponentScan
@EnableScheduling
@Configuration
public class ScheduledExample {
public static void main(String[] args) throws InterruptedException {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
ScheduledExample.class);
}
}
OutputRunning scheduled task thread: pool-1-thread-1, time: 16:21:19.109535400 Running scheduled task 2 thread: pool-1-thread-1, time: 16:21:19.110531900 Running scheduled task thread: pool-1-thread-1, time: 16:21:20.111538 Running scheduled task 2 thread: pool-1-thread-1, time: 16:21:21.111861600 Running scheduled task thread: pool-1-thread-1, time: 16:21:21.113261100 Running scheduled task thread: pool-1-thread-1, time: 16:21:22.118375900 Running scheduled task 2 thread: pool-1-thread-1, time: 16:21:23.116426400 Running scheduled task thread: pool-1-thread-1, time: 16:21:23.132031500 Running scheduled task thread: pool-1-thread-1, time: 16:21:24.144552200 Running scheduled task 2 thread: pool-1-thread-1, time: 16:21:25.133099900 Running scheduled task thread: pool-1-thread-1, time: 16:21:25.149102700 Running scheduled task thread: pool-1-thread-1, time: 16:21:26.158072 Running scheduled task 2 thread: pool-1-thread-1, time: 16:21:27.141515600 Running scheduled task thread: pool-1-thread-1, time: 16:21:27.172455200 .....................
Example ProjectDependencies and Technologies Used: - spring-context 6.2.12 (Spring Context)
Version Compatibility: 3.2.9.RELEASE - 6.2.12 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 25
- Maven 3.9.11
|
|