一、异步任务
首先建立一个web项目
package com.my.controller;
import com.my.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.xml.ws.Action;
@Controller
public class AsyncController {
@Autowired
AsyncService asyncService;
//告诉Spring这是一个异步的方法
@RequestMapping("/hello")
@ResponseBody
public String Hello(){
asyncService.hello();
return "ok";
}
}
package com.my.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(("休眠。。。。"));
}
}
开启多线程之后先休眠三秒之后再打印休眠再返回ok
使用SpringBoot异步注解之后就可以异步执行
开启异步之后同时返回ok和执行hello方法需要休眠3秒之后再打印”休眠。。。“
二、定时任务
TaskScheduler 任务调度
TaskExecutor 任务执行
@EnableScheduling//开启定定时任务
@Scheduled //什么时候执行
使用cron表达式