spring scheduled
- Define a method annotated with
@Scheduled
in a Spring component or service class.
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class MyScheduledTask {
@Scheduled(fixedRate = 5000) // Specify the fixed rate in milliseconds
public void myScheduledMethod() {
// Your scheduled task logic goes here
System.out.println("Executing scheduled task...");
}
}
- Enable scheduling in the Spring application configuration.
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
public class AppConfig {
// Configuration class to enable Spring scheduling
}
- Configure the scheduling properties in the application properties file (if needed).
# application.properties
spring.task.scheduling.pool.size=5
spring.task.scheduling.thread-name-prefix=scheduled-task-
These properties are optional and can be adjusted based on your specific requirements.
- Run the Spring Boot application.
Ensure that your Spring Boot application is up and running. The scheduled task will be automatically executed based on the specified fixed rate.
Note: The provided example uses the fixedRate
attribute, but there are other options like fixedDelay
and cron expressions that you can use based on your scheduling needs. Adjust the scheduling annotation and method accordingly.