You know, the Spring framework provides the @Scheduled annotation which can be used to create scheduled tasks in Spring applications. This post will help you understand the usage of this annotation with some code examples.

 

1. Syntax and Usage of @Scheduled Annotation

This annotation is used to mark a method whose code will be scheduled to run either once or periodically, depending on the attributes used. The following example shows a usage of this annotation:

package net.codejava;

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
public class MyTask {

	@Scheduled(initialDelay = 60000)
	public void work() {
		// task execution logic...
		System.out.println("this task will run only once");
	}
}
In this example, the task is scheduled to run only once, after an initial delay of 60 seconds (60,000 milliseconds). That means that if only the initialDelay attribute is used, Spring will interpret it as a one-time task.

Keep in mind that for the @Scheduled annotation to work, you must use the @EnableScheduling annotation somewhere (either in the same task class or in a different one). Additionally, the annotated method must not accept arguments and should have a void return type.

Also note that you must specify at least one attribute when using this annotation: exactly one of the cron, fixedDelay or fixedRate, and optionally an initialDelay. The explanation of these attributes is provided below.


2. Attributes of @Scheduled Annotation

The @Scheduled annotation has several attributes that let you configure behaviors of scheduled tasks to meet different requirements. These attributes are explained below with code examples. 

  • long fixedDelay: specifies a fixed period between the end of the last invocation and the start of the next. This means the next execution of the task will wait for the previous one to complete. Below is an example:
@Scheduled(fixedDelay = 30000)
public void work() {
	// task execution logic...
}
In this example, the task will be executed every 30 seconds. It ensures that there are no overlapping executions running in parallel because the next one must wait for the previous one to complete.

 

  • long fixedRate: specifies a fixed period between invocations of the task. This means every invocation of the task will start exactly at the specified interval, regardless of how long the execution takes. For example:
@Scheduled(fixedRate = 300_000)
public void work() {
	// task execution logic...
	
}


This task is scheduled to run periodically every 5 minutes (300 seconds).

 

  • String cron: specifies a cron-like expression to schedule the task based on second, minute, hour, day of month, month and day of week. Unix fans will find this attribute helpful. For example:
@Scheduled(cron = "0 15 10 L * ?")
public void work() {
	
	// task execution logic...
	
}
In this example, the task will run at 10:15 AM on the last day of every month. Check this article to learn more about the syntax of cron-like expressions.

 

  • long initialDelay: specifies the delay time before the first execution of a fixedRate or fixedDelay task. For example:
@Scheduled(initialDelay = 30_000, fixedDelay = 300_000)
public void work() {

	// task execution logic...

}
In this example, the task will be delayed about 30 seconds before its first invocation.

 

  • TimeUnit timeUnit: specifies the time unit used for intervals (fixed rate, fixed delay, initial delay). The default time unit is milliseconds, but you can change it to minutes, hours, days, etc. For example:
@Scheduled(fixedRate = 5, timeUnit = TimeUnit.HOURS)
public void work() {

	// task execution logic...

}
In this example, the task is scheduled to run every 5 hours. Check the Javadocs of TimeUnit enum for more details.

 

  • String fixedRateString: has same meaning as the fixedRate attribute but accept Spring-style “${…}” placeholders as well as SpEL expressions. Use this attribute if you want to read the interval from a configuration file. For example:
@Scheduled(fixedRateString = "${app.task.fixed.rate}")
public void work() {
	// task execution logic...

}
In this example, the fixed rate value will be read from the property app.task.fixed.rate in the application.properties file. 

  • String fixedDelayString: is similar to fixedRateString, but for fixed delay task.
  • String initialDelayString: is similar to fixedRateString, but for initial delay time.
 

Besides these attributes, the @Scheduled annotation also has scheduler and zone attributes which are less common. You can check the reference docs below to learn more.

 

Reference:

 

You can also watch the following video to see examples of using the @Scheduled annotation in action:

 

Other Spring Annotations:

 

Complete Spring framework Tutorials

 


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment