TaskScheduler

Sometimes, we need to perform a task at fixed intervals, and this can be achieved with the Spring scheduler framework. In this section, we will see how we can schedule a task in Spring with the use of a few annotations.

Let's see a simple example of scheduling a task in the Spring application:

@Configuration
@EnableScheduling
public class SpringSchedulingExample {
private static final Logger LOGGER =
Logger.getLogger(SpringSchedulingExample.class);
@Scheduled(fixedDelay = 2000)
public void scheduledTask() {
LOGGER.info("Execute task " + new Date());
}

public static void main(String[] args) {
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(
SpringSchedulingExample.class);
String scheduledAnnotationProcessor =
"org.springframework.context.annotation.
internalScheduledAnnotationProcessor";
LOGGER.info("ContainsBean : " + scheduledAnnotationProcessor +
": " + context.containsBean(scheduledAnnotationProcessor));
try {
Thread.sleep(12000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
context.close();
}
}
}

In Spring, we can enable task scheduling with the help of the @EnableScheduling annotation. Once task scheduling is enabled, Spring will automatically register an internal bean post processor, which will find the @Scheduled annotated methods on a Spring-managed bean.

In the previous example, we annotated the scheduledTask() method with the @Scheduled annotation with the fixedDelay attribute to be invoked every 2 seconds. We can also use other attributes, such as fixedRate and cron:

@Scheduled(fixedRate = 2000)
@Scheduled(cron = "*/2 * * * * SAT,SUN,MON")

When we compile and run the previous class, we will get the following output:

Execute task Thu May 10 20:18:04 IST 2018
ContainsBean : org.springframework.context.annotation.internalScheduledAnnotationProcessor: true
Execute task Thu May 10 20:18:06 IST 2018
Execute task Thu May 10 20:18:08 IST 2018
Execute task Thu May 10 20:18:10 IST 2018
Execute task Thu May 10 20:18:12 IST 2018
Execute task Thu May 10 20:18:14 IST 2018
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset