Wednesday, December 27, 2017

Spring boot @EnableScheduling and @Scheduled Job Example

Spring boot @EnableScheduling and @Scheduled Job Example

Let’s say you want to run job at every 10 seconds interval. You can achieve this job scheduling in below steps:

1) @EnableScheduling to Spring Boot Application class

Add @EnableScheduling annotation to your spring boot application class. @EnableScheduling is a Spring Context module annotation. It internally imports the SchedulingConfiguration via the @Import(SchedulingConfiguration.class) instruction
@SpringBootApplication
@EnableScheduling
public class SpringBootWebApplication {
     
}

2) Add @Scheduled annotations

Now you can add @Scheduled annotations on methods which you want to scedule. Only condition is that methods should be without arguments.
ScheduledAnnotationBeanPostProcessor that will be created by the imported SchedulingConfigurationscans all declared beans for the presence of the @Scheduled annotations.
For every annotated method without arguments, the appropriate executor thread pool will be created. This thread pool will manage the scheduled invocation of the annotated method.
@Scheduled(initialDelay = 1000, fixedRate = 10000)
public void run() {
    logger.info("Current time is :: " + Calendar.getInstance().getTime());
}
Now observe the output in console:
2017-03-08 15:02:55 - Current time is :: Wed Mar 08 15:02:55 IST 2017
2017-03-08 15:03:05 - Current time is :: Wed Mar 08 15:03:05 IST 2017
2017-03-08 15:03:15 - Current time is :: Wed Mar 08 15:03:15 IST 2017
2017-03-08 15:03:25 - Current time is :: Wed Mar 08 15:03:25 IST 2017
2017-03-08 15:03:35 - Current time is :: Wed Mar 08 15:03:35 IST 2017

No comments:

Post a Comment

உப்பு மாங்காய்

சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...