Spring's @Scheduled annotation allows to use cron expression to schedule tasks.
Example
Bean with @Scheduled method
Following example uses cron expression to schedule a task which repeats every 2 seconds.
package com.logicbig.example;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalTime;
@Component
public class MyBean {
@Scheduled(cron = "*/2 * * * * *")
public void runTask() {
System.out.printf("Running scheduled task " +
" 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) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(
ScheduledExample.class);
}
}
OutputRunning scheduled task thread: pool-1-thread-1, time: 16:09:28.007171400 Running scheduled task thread: pool-1-thread-1, time: 16:09:30.001063100 Running scheduled task thread: pool-1-thread-1, time: 16:09:32.006863900 Running scheduled task thread: pool-1-thread-1, time: 16:09:34.010686 Running scheduled task thread: pool-1-thread-1, time: 16:09:36.014262 .....................
Example ProjectDependencies and Technologies Used: - spring-context 6.2.12 (Spring Context)
Version Compatibility: 4.3.0.RELEASE - 6.2.12 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 25
- Maven 3.9.11
|