Create a Spring MVC project
Open spring tool suiteTest whether the project is working, if it's ok you should see a hello page in your browser.
File > New > Spring Project > Spring Mvc Project
Adding Dependency
Add following to pom.xml.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
Create the scheduler
This is the class you want to schedule. Name it as ScheduledTasks.java and place with homecontroller.javaimport java.text.SimpleDateFormat;reportCurrentTime() methos will be called by Spring Scheduler every 5 seconds as the value set is 5000.
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
public class ScheduledTasks {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate=5000)
public void reportCurrentTime(){
System.out.println("time is : "+dateFormat.format(new Date()));
}
}
Configurations
This sample will use annotation based approach, so we shall create a AppConfig.java class for configurations.import org.springframework.context.annotation.Bean;This @EnableScheduling annotation will ensure all the methods with @scheduled to add to scheduler.
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
public class AppConfig {
@Bean
public ScheduledTasks bean(){
return new ScheduledTasks();
}
}
Execution
Once your run the web application check the console output. You will notice time is been logged every 5 seconds.Further
We can improve our application and change the pool size. Let's change the pool size to 10. Change is made to AppConfig.javaimport java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
@Configuration
@EnableScheduling
public class AppConfig implements SchedulingConfigurer {
@Bean
public ScheduledTasks bean(){
return new ScheduledTasks();
}
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecuter());
}
@Bean(destroyMethod="shutdown")
public Executor taskExecuter() {
return Executors.newScheduledThreadPool(10);
}
}
Comments
Post a Comment