Spring @Scheduled Annotation Example

By Arvind Rai, November 30, 2021
This page will walk through Spring @Scheduled annotation example.
1. The @Scheduled annotation marks a method to be scheduled.
2. The @Scheduled annotation must use either cron or fixedDelay or fixedRate attribute.
3. The @Scheduled annotated method must expect no arguments.
4. This method has typically void return type, if not, the returned value will be ignored when called through the scheduler.
@Scheduled(fixedRate=1000)
public void myWork() {
  ------
} 
5. The @Scheduled annotation has a special cron expression value as CRON_DISABLED introduced in Spring 5.1 that indicates a disabled trigger "-". This is useful for external disabling of corresponding scheduled methods used with ${...} placeholders.
6 The @Scheduled annotation is introduced in Spring 3.0.

Enabling @Scheduled Annotation

The @Scheduled annotation can be enabled by any of the following ways.
1. Use @EnableScheduling annotation on @Configuration classes.
@Configuration
@EnableScheduling
public class AppConfig {
} 
2. Use <task:annotation-driven/> in XML configuration.
3. By registering below class.
ScheduledAnnotationBeanPostProcessor 

Using @Scheduled Annotation

Step-1: Create a class with methods annotated with @Scheduled.
PrintTask.java
package com.concretepage;
import java.util.concurrent.TimeUnit;
import org.springframework.scheduling.annotation.Scheduled;

public class PrintTask {
  @Scheduled(fixedRate = 2, initialDelay = 5, timeUnit = TimeUnit.SECONDS)
  public void print() {
	System.out.println("--- Printing ---");
  }
} 
The print() method is scheduled to run with 5 seconds delay for the first time and then after every 2 seconds.
Step-2: Use @EnableScheduling with @Configuration class.
AppConfig.java
package com.concretepage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling
@Configuration
public class AppConfig {
  @Bean
  public PrintTask printTask() {
	return new PrintTask();
  }
} 
Step-3: Now run the application. We are using Spring Boot to run the example.
SpringBootDemo.java
package com.concretepage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootDemo {
  public static void main(String[] args) {
	SpringApplication.run(SpringBootDemo.class, args);
  }
} 
Output
--- Printing ---
--- Printing ---
--- Printing --- 

@Scheduled Annotation Attributes

The @Scheduled annotation has following attributes.
1. cron : A cron-like expression as string.
@Scheduled(cron="* * * ? * *")
public void print() {
    System.out.println("--- Printing ---");
} 
The method will execute at every second.
2. fixedDelay : Fixed delay as long type between the end of the last invocation and the start of the next.
@Scheduled(fixedDelay = 5000)
public void print() {
  System.out.println("--- Printing ---");
} 
The method will execute with a 5 seconds fixed delay between the end of the last invocation and the start of the next.
3. fixedDelayString : Same as fixedDelay but with string value.
@Scheduled(fixedDelayString = "5000")
public void print() {
  System.out.println("--- Printing ---");
} 
4. fixedRate : Method will execute with a fixed period as long type between invocations.
@Scheduled(fixedRate = 1000)
public void print() {
  System.out.println("--- Printing ---");
} 
Method will execute with 1 second fixed period between invocations.
5. fixedRateString : Same as fixedRate but with string value.
@Scheduled(fixedRateString = "1000")
public void print() {
  System.out.println("--- Printing ---");
} 
6. initialDelay : Time to delay in long type before the first execution of a fixedRate() or fixedDelay() task.
@Scheduled(fixedRate = 1000, initialDelay = 5000)
public void print() {
  System.out.println("--- Printing ---");
} 
The first execution of the method will start after 5 seconds and then keep executing on 1 second fixed rate.
7. initialDelayString : Same as initialDelayString but with string value.
@Scheduled(fixedRate = 1000, initialDelayString = "5000")
public void print() {
  System.out.println("--- Printing ---");
} 
8. timeUnit: The unit of time as TimeUnit. If timeUnit attribute is not provided, then TimeUnit.MILLISECONDS is considered as default.
@Scheduled(fixedRate = 1, initialDelay = 2, timeUnit = TimeUnit.MINUTES)
public void print() {
  System.out.println("--- Printing ---");
} 
The method will start to execute with 2 minutes initial delay and then keep executing with 1 minute fixed rate.
9. zone : A time zone for which the cron expression will be resolved. By default server local time zone is used.
@Scheduled(cron = "* * * ? * *", zone = "Asia/Singapore")
public void print() {
  System.out.println("--- Printing ---");
} 

With @Component

We can use @Scheduled annotation in @Component class.
Suppose PrintTask is annotated by @Component.
PrintTask.java
@Component
public class PrintTask {
  @Scheduled(fixedRate = 2, initialDelay = 5, timeUnit = TimeUnit.SECONDS)
  public void print() {
	System.out.println("--- Printing ---");
  }
} 
Then @ComponentScan should be used on @Configuration class.
AppConfig.java
@ComponentScan("com.concretepage")
@EnableScheduling
@Configuration
public class AppConfig {
} 

Using @Scheduled Annotation in @Configuration Class

The @Scheduled method can be created in @Configuration classes.
AppConfig.java
@EnableScheduling
@Configuration
public class AppConfig {
  @Scheduled(fixedRate = 2, initialDelay = 5, timeUnit = TimeUnit.SECONDS)
  public void print() {
	System.out.println("--- Printing ---");
  }
} 

Using SchedulingConfigurer

1. Using SchedulingConfigurer, we can specify TaskScheduler bean to be used when executing scheduled tasks. It is useful when more control is desired.
2. The SchedulingConfigurer is implemented by @Configuration classes annotated with @EnableScheduling.
3. By default, Spring searches for an associated scheduler definition, either a unique TaskScheduler bean in the context, or a TaskScheduler bean named "taskScheduler". If neither of two is available, a local single-threaded default scheduler is created and used within the registrar.
4. The SchedulingConfigurer allows access to the underlying ScheduledTaskRegistrar instance.

Find the example.
AppConfig.java
@ComponentScan("com.concretepage")
@EnableScheduling
@Configuration
public class AppConfig implements SchedulingConfigurer {
  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
      taskRegistrar.setScheduler(taskExecutor());
  }

  @Bean(destroyMethod="shutdown")
  public Executor taskExecutor() {
      return Executors.newScheduledThreadPool(50);
  }  
} 

References

Annotation Type Scheduled
Annotation Type EnableScheduling

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us