异步任务
在主程序开启异步
@EnableAsync
异步测试类
@Service
public class AsyncService {
//告诉spring这是一个异步的方法
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理");
}
}
controller
@RestController
public class AsyncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){//停止三秒
asyncService.hello();
return "ok";
}
}
如果hello方法不加@Async注解的话页面就会等三秒在输出ok 如果有这个铸就就会知道这是一个异步任务就会开启多线程
定时执行
在程序入口开启定时
@EnableScheduling//开启定时功能的注解
在方法上加@Scheduled用cron表达式
@Service
public class ScheduledService {
//在一个特定的时间执行这个方法
//cron表达式
//秒 分 时 日 月 周几
//每天21点49分50秒生成 ?的意思是无论你写什么都是无效的
//比如 13 13 14 20 * ? 不用管20号是星期几
@Scheduled(cron = "40 57 21 * * *")
public void hello(){
System.out.println("你被捕了哈哈哈哈哈哈·1");
}
}