Original title: Spring certified China Education Management Center - learn how to use spring to arrange tasks (spring China Education Management Center)

This guide will guide you through the steps of scheduling tasks using Spring.
What will you build
@Scheduled you will build an application that prints the current time every five seconds using Spring comments.
What do you need?
- About 15 minutes
- Favorite text editor or IDE
- JDK 1.8 or later
- Gradle 4 + or Maven 3.2+
- You can also import the code directly into the IDE: spring tool kit (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 the basic setup steps you are already familiar with. Either way, you'll end up with working code.
To start from scratch, continue with Spring Initializr.
To skip the basics:
- 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
- The CD goes to GS scheduling tasks / initial
- Jump to create scheduled task.
When finished, you can check the results against the code in gs-scheduling-tasks/complete.
Start with Spring Initializr
You can use this pre initialized project and click Generate to download the ZIP file. This project is configured to fit the examples in this tutorial.
Manually initialize the project:
- Navigate to https://start.spring.io . The service extracts all the dependencies required by the application and completes most of the settings for you.
- Select Gradle or Maven and the language you want to use. This guide assumes that you have chosen Java.
- Click generate.
- Download the generated ZIP file, which is an archive of the Web application configured according to your choice.
If your IDE has spring initializer integration, you can complete this process from your IDE.
You can also fork the project from Github and open it in your IDE or other editor.
Add awaitity dependency
Testing in complete/src/test/java/com/example/schedulingtasks/ScheduledTasksTest.java requires awaitity library.
A later version of the awaitility library is not suitable for this test, so you must specify version 3.1.2.
To add the awaitility library to Maven, add the following dependencies:
<dependency> <groupId>org.awaitility</groupId> <artifactId>awaitility</artifactId> <version>3.1.2</version> <scope>test</scope> </dependency>
The following listing shows the completed POM XML file:
<?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.5.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>scheduling-tasks-complete</artifactId> <version>0.0.1-SNAPSHOT</version> <name>scheduling-tasks-complete</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> <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 dependencies:
testImplementation 'org.awaitility:awaitility:3.1.2'
The following listing shows the completed build Gradle file:
plugins { id 'org.springframework.boot' version '2.5.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 scheduled task
Now that you have set up the project, you can create a scheduled task. The following list (from src/main/java/com/example/schedulingtasks/ScheduledTasks.java) shows how to do this:
/* * 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())); } }
Comments define when a Scheduled specific method runs. This example uses fixedRate, which specifies the interval between method calls, measured from the start time of each call. There are other options, such as fixedDelay, which specifies the interval between calls measured from the completion of the task. You can also use @ Scheduled(cron = "..") Expression for more complex task scheduling.
Enable schedule
Although scheduling tasks can be embedded in Web applications and WAR files, a simpler approach (shown in the next listing) creates a separate application. To do this, package everything into an executable JAR file driven by the good old Javamain() method. The following list (from src/main/java/com/example/schedulingtasks/SchedulingTasksApplication.java) shows the application classes:
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 convenient annotation that adds all of the following:
- @Configuration: marks the class as the bean definition source of the application context.
- @EnableAutoConfiguration: Tell Spring Boot to start adding beans according to classpath settings, other beans and various property settings. For example, if spring webmvc is on the classpath, this annotation marks the application as a Web application and activates key behaviors, such as setting DispatcherServlet
- @ComponentScan: Tell Spring to find other components, configurations and services com/example in the package and let it find the controller.
The main() method uses springapplication. Of Spring Boot Run () method to start the application. Have you noticed that there is no single line of XML? There is no Web XML file. This Web application is 100% pure Java, and you don't have to deal with any pipeline or infrastructure configuration.
@The enableshcheduling annotation ensures that a background task executor is created. Without it, nothing will be arranged.
Build an executable JAR
You can run the application from the command line using Gradle or Maven. You can also build and run a single executable jar file that contains all the necessary dependencies, classes, and resources. Building executable jars can be easily used as application delivery, versioning and deployment services throughout the development life cycle, across different environments, and so on.
If you use Gradle, you can use/ gradlew bootRun. Alternatively, you can use to build JAR files/ gradlew build, and then run the} JAR file as follows:
java -jar build/libs/gs-scheduling-tasks-0.1.0.jar
If you use Maven, you can use/ mvnw spring-boot:run. Alternatively, you can use the build JAR file/ mvnw clean package and run the JAR file as follows:
java -jar target/gs-scheduling-tasks-0.1.0.jar
The steps described here create a runnable JAR. You can also build classic WAR files.
The log output is displayed, and you can see from the log that it is on the background thread. You should see that your scheduled tasks are triggered every} five seconds. The following list shows typical output:
... 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 ...
congratulations! You created an application with scheduled tasks. In addition, this technology is suitable for any type of application.