Home  >  Spring Core

Example of @EnableScheduling in Spring

By Arvind Rai, March 21, 2013
Spring provides @EnableScheduling annotation. We can achieve scheduling of the task. @EnableScheduling is used with @Configuration in XML free bean creation. The beans which need to be scheduled must have @Scheduled annotaion. We need to configure schedule time. It is configured as @Scheduled(fixedRate=2000). This configuration means a thread will run the task every after two second.

Find the link for task scheduler using XML configuration.

Find the example for @EnableScheduling below.
Task.java
package com.concretepage;
import org.springframework.scheduling.annotation.Scheduled;
public class Task {
	@Scheduled(fixedRate=2000)
	public void doTask(){
		System.out.println("do some task");
	}
} 

AppConfig.java
package com.concretepage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
public class AppConfig {
	@Bean
	public Task task() {
		return new Task();
	}
} 

AppTest.java
package com.concretepage;
import java.sql.SQLException;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
public class AppTest {
	public static void main(String[] args) throws SQLException {
		ApplicationContext context = SpringApplication.run(AppConfig.class);
	}
} 

Output
do some task
do some task
do some task
do some task
do some task
------------
------------ 

build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'SpringDemo'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
    compile 'org.springframework.boot:spring-boot-starter:1.2.7.RELEASE'
}  

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us