You are on page 1of 9

2/19/2021 Getting Started | Scheduling Tasks

ALL GUIDES

Scheduling Tasks
This guide walks you through the steps for scheduling tasks with Spring.

What You Will Build


You will build an application that prints out the current time every ve seconds by using
Spring’s @Scheduled annotation.

What You Need


About 15 minutes

A favorite text editor or IDE

JDK 1.8 or later

Gradle 4+ or Maven 3.2+

You can also import the code straight into your IDE:

Spring Tool Suite (STS)

IntelliJ IDEA

How to complete this guide


Like most Spring Getting Started guides, you can start from scratch and complete each
step or you can bypass basic setup steps that are already familiar to you. Either way, you
end up with working code.

To start from scratch, move on to Starting with Spring Initializr.

To skip the basics, do the following:

https://spring.io/guides/gs/scheduling-tasks/ 1/9
2/19/2021 Getting Started | Scheduling Tasks

Download and unzip the source repository for this guide, or clone it using Git:
git clone https://github.com/spring-guides/gs-scheduling-tasks.git

cd into gs-scheduling-tasks/initial

Jump ahead to Create a Scheduled Task.

When you nish, you can check your results against the code in
gs-scheduling-tasks/complete .

Starting with Spring Initializr


For all Spring applications, you should start with the Spring Initializr. The Initializr o ers a
fast way to pull in all the dependencies you need for an application and does a lot of the
setup for you. This example needs no Spring dependencies. Spring Boot itself provides all
the Spring packages that you need for this guide.

You can get a Maven build le with the necessary dependencies directly from the Spring
Initializr. The following listing shows the pom.xml le that is created when you choose
Maven:

COPY
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>scheduling-tasks</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>scheduling-tasks</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

https://spring.io/guides/gs/scheduling-tasks/ 2/9
2/19/2021 Getting Started | Scheduling Tasks

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-
plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

You can get a Maven build le with the necessary dependencies directly from the Spring
Initializr. The following listing shows the build.gradle le that is created when you
choose Gradle:

COPY
plugins {
id 'org.springframework.boot' version '2.4.2'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
mavenCentral()
}

dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation('org.springframework.boot:spring-boot-starter-test')
}

test {
useJUnitPlatform()
}

Adding the awaitility Dependency

The tests in
complete/src/test/java/com/example/schedulingtasks/ScheduledTasksTest.java
require the awaitility library.

https://spring.io/guides/gs/scheduling-tasks/ 3/9
2/19/2021 Getting Started | Scheduling Tasks

Later versions of the awaitility library do not work for this test, so you have to
specify version 3.1.2.

To add the awaitility library to Maven, add the following dependency:

COPY
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>3.1.2</version>
<scope>test</scope>
</dependency>

The following listing shows the nished pom.xml le:

COPY
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>scheduling-tasks</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>scheduling-tasks</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>3.1.2</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
https://spring.io/guides/gs/scheduling-tasks/ 4/9
2/19/2021 Getting Started | Scheduling Tasks

<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-
plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

To add the awaitility library to Gradle, add the following dependency:

COPY
testImplementation 'org.awaitility:awaitility:3.1.2'

The following listing shows the nished build.gradle le:

COPY
plugins {
id 'org.springframework.boot' version '2.4.2'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
mavenCentral()
}

dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.awaitility:awaitility:3.1.2'
testImplementation('org.springframework.boot:spring-boot-starter-test')
}

test {
useJUnitPlatform()
}

Create a Scheduled Task


Now that you have set up your project, you can create a scheduled task. The following
listing (from src/main/java/com/example/schedulingtasks/ScheduledTasks.java ) shows
how to do so:
https://spring.io/guides/gs/scheduling-tasks/ 5/9
2/19/2021 Getting Started | Scheduling Tasks

COPY
/*
* Copyright 2012-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.schedulingtasks;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTasks {

private static final Logger log =


LoggerFactory.getLogger(ScheduledTasks.class);

private static final SimpleDateFormat dateFormat = new


SimpleDateFormat("HH:mm:ss");

@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}
}

The Scheduled annotation de nes when a particular method runs.

This example uses fixedRate , which speci es the interval between method
invocations, measured from the start time of each invocation. There are other
options, such as fixedDelay , which speci es the interval between invocations
measured from the completion of the task. You can also use
@Scheduled(cron=". . .") expressions for more sophisticated task scheduling.

https://spring.io/guides/gs/scheduling-tasks/ 6/9
2/19/2021 Getting Started | Scheduling Tasks

Enable Scheduling
Although scheduled tasks can be embedded in web applications and WAR les, the simpler
approach (shown in the next listing) creates a standalone application. To do so, package
everything in a single, executable JAR le, driven by a good old Java main() method. The
following listing (from
src/main/java/com/example/schedulingtasks/SchedulingTasksApplication.java ) shows
the application class:

COPY
package com.example.schedulingtasks;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class SchedulingTasksApplication {

public static void main(String[] args) {


SpringApplication.run(SchedulingTasksApplication.class);
}
}

@SpringBootApplication is a convenience annotation that adds all of the following:

@Configuration : Tags the class as a source of bean de nitions for the application
context.

@EnableAutoConfiguration : Tells Spring Boot to start adding beans based on


classpath settings, other beans, and various property settings. For example, if
spring-webmvc is on the classpath, this annotation ags the application as a web
application and activates key behaviors, such as setting up a DispatcherServlet .

@ComponentScan : Tells Spring to look for other components, con gurations, and
services in the com/example package, letting it nd the controllers.

The main() method uses Spring Boot’s SpringApplication.run() method to launch an


application. Did you notice that there was not a single line of XML? There is no web.xml
le, either. This web application is 100% pure Java and you did not have to deal with
con guring any plumbing or infrastructure.

The @EnableScheduling annotation ensures that a background task executor is created.


Without it, nothing gets scheduled.

https://spring.io/guides/gs/scheduling-tasks/ 7/9
2/19/2021 Getting Started | Scheduling Tasks

Build an executable JAR

You can run the application from the command line with Gradle or Maven. You can also
build a single executable JAR le that contains all the necessary dependencies, classes, and
resources and run that. Building an executable jar makes it easy to ship, version, and
deploy the service as an application throughout the development lifecycle, across di erent
environments, and so forth.

If you use Gradle, you can run the application by using ./gradlew bootRun . Alternatively,
you can build the JAR le by using ./gradlew build and then run the JAR le, as follows:

java -jar build/libs/gs-scheduling-tasks-0.1.0.jar

If you use Maven, you can run the application by using ./mvnw spring-boot:run .
Alternatively, you can build the JAR le with ./mvnw clean package and then run the JAR
le, as follows:

java -jar target/gs-scheduling-tasks-0.1.0.jar

The steps described here create a runnable JAR. You can also build a classic WAR
le.

Logging output is displayed, and you can see from the logs that it is on a background
thread. You should see your scheduled task re every ve seconds. The following listing
shows typical output:

COPY
...
2019-10-02 12:07:35.659 INFO 28617 --- [ scheduling-1]
c.e.schedulingtasks.ScheduledTasks : The time is now 12:07:35
2019-10-02 12:07:40.659 INFO 28617 --- [ scheduling-1]
c.e.schedulingtasks.ScheduledTasks : The time is now 12:07:40
2019-10-02 12:07:45.659 INFO 28617 --- [ scheduling-1]
c.e.schedulingtasks.ScheduledTasks : The time is now 12:07:45
2019-10-02 12:07:50.657 INFO 28617 --- [ scheduling-1]
c.e.schedulingtasks.ScheduledTasks : The time is now 12:07:50
...

Summary

https://spring.io/guides/gs/scheduling-tasks/ 8/9
2/19/2021 Getting Started | Scheduling Tasks

Congratulations! You created an application with a scheduled task. Also, this technique
works in any type of application.

See Also
The following guides may also be helpful:

Building an Application with Spring Boot

Creating a Batch Service

Want to write a new guide or contribute to an existing one? Check out our contribution
guidelines.

All guides are released with an ASLv2 license for the code, and an Attribution,
NoDerivatives creative commons license for the writing.

https://spring.io/guides/gs/scheduling-tasks/ 9/9

You might also like