[JAVA] Spring Boot tutorial task schedule

I created a program to execute tasks regularly by referring to the official Spring boot tutorial (Task Schedule).

environment

Apache Maven 3.6.3 OS: macOS Mojave version 10.14.6 Text editor: VSCode Java: 11.0.2

Create

First, open Spring Initializr and create a foundation with the following contents.

スクリーンショット 2020-07-14 10.56.39.png

Unzip the resulting zip file and open it in an editor.

Add the following dependency to pom.xml.

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

Awaitility is a * library that provides a simple domain-specific language (DSL) for asynchronous system testing *. (From Introduction to Awaitility)

Create a ScheduledTasks.java file under src / main / java / com / example / schedulingtasks.

The contents are as follows.

ScheduledTasks.java


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()));
	}
}

fixedRate specifies the method call interval, measured from the start time of each call. Other options, such as fixedDeley, specify the interval between calls from task completion.

@Scheduled Run the task periodically. You can choose from a variety of options (table below). Specify the execution cycle with the Scheduled annotation for the task you want to execute periodically. This annotation can only be specified for methods that take no arguments. (It does not result in a compile error, but an exception occurs at runtime.)

This time I'll run the task every 5 seconds with fixedRate.

field description
fixedDelay How many milliseconds after the method was last executed.
fixedRate How many milliseconds after the method's last execution start time.
initialDelay Wait time for the first execution of a method.
cron Write cron and set the schedule. You can also specify the time zone using zone.

You can also use (cron = "...") for more advanced settings.

Logger and LoggerFactory are for outputting the result to console. You can display the log by specifying the class in the argument of LoggerFactory.getLogger ().

Then add the code to the automatically created SchedulingTasksApplication.java file under src / main / java / com / example / schedulingtasks /.

The contents are as follows.

SchedulingTasksApplication.java


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 This is a convenient annotation that works as an annotation for three. It contains the following three annotations.

@Configuration You can register additional beans in the context and import additional configuration classes.

@Bean It is for returning the class instantiated by the method that describes @Bean.

@EnableAutoConfiguration Enables the Spring Boot automatic configuration mechanism.

@ComponentScan It looks for other components, settings, etc. in the package and tells Spring to find the controller.

@EnableScheduling Enable the schedule.

Execute

The code is now complete. I will execute it with the following command at once.

./mvnw spring-boot:run

The task is running every 5 seconds. スクリーンショット 2020-07-14 10.32.52.png

It was easy to create without adding any dependencies!

Recommended Posts

Spring Boot tutorial task schedule
Spring Boot Tutorial Using Spring Security Authentication
[Tutorial] Spring Batch
Challenge Spring Boot
Spring Boot Form
Spring Boot Memorandum
gae + spring boot
Annotations used in Spring Boot task management tool
View the Gradle task in the Spring Boot project
SPRING BOOT learning record 01
[I tried] Spring tutorial
Spring Boot + Heroku Postgres
Spring boot memo writing (1)
First Spring Boot (DI)
SPRING BOOT learning record 02
Spring Boot2 cheat sheet
Spring Boot exception handling
Spring Boot Servlet mapping
Spring boot development-development environment-
Spring Boot learning procedure
Learning Spring Boot [Beginning]
Spring boot memo writing (2)
Spring Boot 2.2 Document Summary
[Spring Boot] DataSourceProperties $ DataSourceBeanCreationException
Spring Boot 2.3 Application Availability
Spring boot tutorials Topics
Download with Spring Boot
[Spring Boot] Environment construction (macOS)
Set context-param in Spring Boot
Try Spring Boot from 0 to 100.
Generate barcode with Spring Boot
Hello World with Spring Boot
Spring Boot on Microsoft Azure
Implement GraphQL with Spring Boot
Spring 5 & Spring Boot 2 Hands-on preparation procedure
Get started with Spring boot
Hello World with Spring Boot!
Spring Boot 2 multi-project in Gradle
[Spring Boot] Web application creation
spring boot port duplication problem
Run LIFF with Spring Boot
SNS login with Spring Boot
Spring Boot Hot Swapping settings
[Java] Thymeleaf Basic (Spring Boot)
Introduction to Spring Boot ① ~ DI ~
File upload with Spring Boot
Spring Boot starting with copy
Introduction to Spring Boot ② ~ AOP ~
CICS-Run Java application-(4) Spring Boot application
Spring Boot starting with Docker
Spring Boot + Springfox springfox-boot-starter 3.0.0 Use
Spring Boot DB related tips
Hello World with Spring Boot
Set cookies with Spring Boot
[Spring Boot] Easy paging recipe
Use Spring JDBC with Spring Boot
Docker × Spring Boot environment construction
Major changes in Spring Boot 1.5
Add module with Spring Boot
Getting Started with Spring Boot
NoHttpResponseException in Spring Boot + WireMock