Using timed tasks in springboot

    Scheduled tasks are generally used in projects and can be used to process some special tasks regularly.

Using timed tasks in spirngboot is very simple, just add an @EnableScheduling annotation to the startup class. By default, if nothing is configured , it will cause a problem. All timing tasks in the system are executed using one thread, that is, if there are 2 timing tasks that need to be executed at the same time, Then only one scheduled task can be executed. If you want to solve this problem, you can define a custom task scheduling thread pool.

solution:

The above picture is taken from the explanation on the annotation class org.springframework.scheduling.annotation.EnableScheduling . Basically, we can solve this problem by defining a bean of type TaskScheduler.

 

Implementation function:

   Start 3 timed tasks, print out a sentence every 1s, and watch whether it is printed by the same thread or a different thread.

Implementation function :

  1. Add the @EnableScheduling annotation to the startup class

  2. Configure a bean of type TaskScheduler (you can delete this type of bean and see the output of the program)

  3. Write a task class to output content every 1s

 

First, the content of the pom 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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.huan</groupId>
	<artifactId>springboot-task</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springboot-task</name>
	<description>spring boot integration timing task+</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.8.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</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>

 2. Writing startup classes

 3. Writing task classes

 4. Execution results

 
 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326594134&siteId=291194637