Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3568

The @Scheduled Annotation in Spring

$
0
0

1. Overview

In this article we’ll discuss the Spring @Scheduled annotation – we will illustrate how it can be used to configure and schedule tasks.

The simple rules that need to be followed to annotate a method with @Scheduled are:

  • method should have void return type
  • method should not accept any parameters

2. Enable Support for Scheduling

To enable the support for scheduling tasks and the @Scheduled annotation in Spring – we can use the Java enable-style annotation:

@Configuration
@EnableScheduling
public class SpringConfig {
    ...
}

Or we can do the same in XML:

<task:annotation-driven>

3. Schedule Task at Fixed Delay

Let’s start by configuring a task to run after a fixed delay:

@Scheduled(fixedDelay = 1000)
public void scheduleFixedDelayTask() {
    System.out.println("Fixed delay task - " + System.currentTimeMillis()/1000);
}

In this case, the duration between the end of last execution and the start of next execution is fixed. The task always waits until the previous one is finished.

This option should be used when it’s mandatory that the previous execution is completed before running again.

4. Schedule Task at a Fixed Rate

Let’s not execute a task at a fixed interval of time:

@Scheduled(fixedRate = 1000)
public void scheduleFixedRateTask() {
    System.out.println("Fixed rate task - " + System.currentTimeMillis()/1000);
}

Note that the beginning of the task execution doesn’t wait for the completion of the previous execution.

This option should be used when each execution of the task is independent.

5. Schedule Task with Initial Delay

Next – let’s schedule a task with a delay (in milliseconds):

@Scheduled(fixedDelay = 1000, initialDelay = 1000)
public void scheduleFixedRateWithInitialDelayTask() {
    long now = System.currentTimeMillis() / 1000;
    System.out.println("Fixed rate task with one second initial delay - " + now);
}

Note how we’re using both fixedDelay as well as initialDelay in this example. The task will be executed a first time after the initialDelay value – and it will continue to be executed according to the fixedDelay.

This option comes handy when the task has set-up that need to be completed.

6. Schedule Task using Cron Expressions

Sometimes delays and rates are not enough, and we need the flexibility of a cron expression to control the schedule of our tasks:

@Scheduled(cron = "0 15 10 15 * ?")
public void scheduleTaskUsingCronExpression() {
    long now = System.currentTimeMillis() / 1000;
    System.out.println("schedule tasks using cron jobs - " + now);
}

Note – in this example, that we’re scheduling a task to be executed at 10:15 AM on the 15th day of every month.

7. Parameterizing the Schedule

Hardcoding these schedules is simple, but usually you need to be able to control the schedule without re-compiling and re-deploying the entire app.

We’ll make use of Spring Expressions to externalize the configuration of the tasks – and we’ll store these in properties files:

A fixedDelay task:

@Scheduled(fixedDelayString = "${fixedDelay.in.milliseconds}")

A fixedRate task:

@Scheduled(fixedRateString = "${fixedRate.in.milliseconds}")

A cron expression based task:

@Scheduled(cron = "${cron.expression}")

8. Configuring scheduled tasks using XML

Spring also provides XML way of configuring the scheduled tasks – here is the XML configuration to set these up:

<!-- Configure the scheduler -->
<task:scheduler id="myScheduler" pool-size="10" />

<!-- Configure the fixedDealy, fixedRate or cron based schduled tasks -->
<task:scheduled-tasks scheduler="myScheduler">
    <task:scheduled ref="beanA" method="methodA" fixed-delay="5000" initial-delay="1000" />
    <task:scheduled ref="beanB" method="methodB" fixed-rate="5000" />
    <task:scheduled ref="beanC" method="methodC" cron="*/5 * * * * MON-FRI" />
</task:scheduled-tasks>

9. Conclusion

In this article we understood the way to configure and use @Scheduled annotation. We covered the process to enable scheduling and various ways to configure scheduling task patterns.


Viewing all articles
Browse latest Browse all 3568

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>