springboot异步任务、定时任务

打开浏览器 http://localhost:8080/hello   ,连续刷新可以看到不会 等待 3秒时间了,pom.xml controller service 代码如下。

-----------Springboot04TaskApplication.java:-----------
@EnableAsync //开启异步注解功能
@EnableScheduling //开启基于注解的定时任务
@SpringBootApplication
public class Springboot04TaskApplication {

public static void main(String[] args) {
SpringApplication.run(Springboot04TaskApplication.class, args);
}

}
-----------AsyncService.java:-----------
@Service
public class AsyncService {

//告诉spring这是一个异步方法
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("处理数据中...");
}
}
-----------ScheduledService.java-----------
@Service
public class ScheduledService {

/**
* second , minute,hour,day of month,month,and day of week.
* 0 * * * * MON-FRI
*
* */
//@Scheduled(cron = "0 * * * * MON-FRI")
//@Scheduled(cron = "0,1,2,3,4,5 * * * * MON-FRI")
//Scheduled(cron = "0-5 * * * * MON-FRI")
@Scheduled(cron = "0/4 * * * * MON-FRI") //每4秒执行一次
public void helllo(){
System.out.println("hello...");
}
}
-----------AsyncController.java-------------------
@RestController
public class AsyncController {

@Autowired
AsyncService asyncService;

@GetMapping("/hello")
public String hello(){
asyncService.hello();
return "success";
}
}
----------------------pom.xml----------------------
<?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.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.自定义</groupId>
<artifactId>springboot-04-task</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-04-task</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-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

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

</project>

猜你喜欢

转载自www.cnblogs.com/belen87/p/11920487.html