Springboot(十六)——异步任务、定时任务
异步任务
1、环境搭建
2、编写service层,实现延迟3000毫秒
package com.study.service;
//加群1025684353一起吹水聊天
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("数据正在处理。。。。");
}
}
3、编写controller,调用service层
package com.study.controller;
import com.study.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//加群1025684353一起吹水聊天
@RestController
public class AstncController {
@Autowired
AsyncService asyncService;
@RequestMapping("/hello")
public String hello(){
asyncService.hello();//延迟三秒
return "ok";
}
}
运行测试
跳转到localhost:8080/hello 的时候会延迟(转圈)三秒
解决办法,在springboot中开启异步功能
1、在主启动类开启异步功能
@SpringBootApplication
@EnableAsync //开启异步注解功能
public class Springboot09TestApplication {
//加群1025684353一起吹水聊天
public static void main(String[] args) {
SpringApplication.run(Springboot09TestApplication.class, args);
}
}
2、在service层方法中添加注解
@Service
public class AsyncService {
//告诉spring这是一个异步的方法,执行这个方法的时候会自动开启线程池
@Async
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();//加群1025684353一起吹水聊天
}
System.out.println("数据正在处理。。。。");
}
}
3、运行测试
定时任务
1、在主启动类添加开启定时任务功能的注解
@SpringBootApplication
@EnableAsync //开启异步注解功能
@EnableScheduling //开启定时功能
public class Springboot09TestApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot09TestApplication.class, args);
}
}
2、编写service层,测试定时任务功能
@Service
public class ScheduledService {
//@Scheduled : 什么时候执行
//在一个特定时间执行这个方法:Timer
//cron表达式 秒 分 时 月 日 星期
/*
0 35 2 * * ? 每天凌晨2:35分执行
0 0/5 10,18 * * ? 每天10点和18点,每隔5分钟执行一次
0 15 10 ? * 1-6 每个月的周一到周六10点15分执行一次
*/
//每隔两秒执行一次
@Scheduled(cron = "0/2 * * * * ?")
public void hello(){
System.out.println("hello被执行了");
}
}
3、运行测试