Spring @EnableScheduling Annotation
November 26, 2021
On this page we will learn using Spring @EnableScheduling
annotation.
1. The
@EnableScheduling
enables scheduled task execution capability.
2. The
@EnableScheduling
is used on @Configuration
classes.
3. The
@Scheduled
annotation is used to mark a method to be scheduled.
4. The
<task:annotation-driven>
XML namespace is equivalent to @EnableScheduling
annotation.
5. The
@EnableScheduling
is introduced in Spring 3.1.
6. The
@EnableScheduling
is used as following.
@Configuration @EnableScheduling public class AppConfig { ------ }
Using @EnableScheduling
AppConfig.javapackage 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(); } }
package com.concretepage; import org.springframework.scheduling.annotation.Scheduled; public class Task { @Scheduled(fixedRate=2000) public void doTask(){ System.out.println("do some task"); } }
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); } }
do some task do some task do some task do some task do some task ------------ ------------
apply plugin: 'java' apply plugin: 'eclipse' archivesBaseName = 'SpringDemo' version = '1' repositories { mavenCentral() } dependencies { compile 'org.springframework.boot:spring-boot-starter:2.5.5' }