SpringBoot开启异步任务只需要两步配置:
1、在主类上加上注解@EnableAsync开启异步功能
2、在service层的方法上加上注解@Async指定调用方法时是异步的
SpringBoot开启定时任务也只需两步配置:
1、在主类上加上注解@EnableScheduling开启定时功能
2、在service层的方法上@Scheduled(cron = "0/5 * * * * MON-SAT")指定定时调用该方法
具体任务如下:
1、在主类上加上注解@EnableAsync开启异步功能
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableAsync
@EnableScheduling
@SpringBootApplication
public class SpringBoot04TaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot04TaskApplication.class, args);
}
}
2、在service层的方法上加上注解@Async指定调用方法时是异步的
package com.example.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
@Async
public void hello(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("处理数据中");
}
}
为了进行测试,添加controller层代码如下:
package com.example.controller;
import com.example.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
asyncService.hello();
return "成功";
}
}
页面访问进行测试,发现没有加异步注解的时候,5秒后控制台打印处理数据中,页面也是需要5秒后才能显示成功;
而使用了异步注解之后,页面可直接显示成功,5秒后控制台打印处理数据中,说明调用service的异步方法时是单独启用了一个线程。
1、在主类上加上注解@EnableScheduling开启定时功能
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableAsync
@EnableScheduling
@SpringBootApplication
public class SpringBoot04TaskApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot04TaskApplication.class, args);
}
}
2、在service层的方法上@Scheduled(cron = "0/5 * * * * MON-SAT")指定定时调用该方法
package com.example.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduledService {
//second, minute, hour, day of month, month, and day of week.
//"0 * * * * MON-FRI"
//0到4秒都运行
// @Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
// @Scheduled(cron = "0-4 * * * * MON-SAT")
//0秒开始,每隔5秒运行一次
@Scheduled(cron = "0/5 * * * * MON-SAT")
public void hello(){
System.out.println("hello.......");
}
}
如有理解不到之处,望指正;