SpringBoot 学习
异步任务
-
核心注解
- 在需要设置异步任务的方法上面添加注解@Async
- 在SpringBoot的启动类上面增加注解 @EnableAsync
-
代码demo
异步服务提供类
/**
* @author echoqian
* @date 2020/4/13 11:07 下午
*/
@Component
public class CaculateHandler {
// 模拟复杂的计算场景 时间假设需要
// 添加异步注解
@Async
public int caculate() throws InterruptedException {
TimeUnit.SECONDS.sleep(3);
return 100;
}
}
Controller层
/**
* @author echoqian
* @date 2020/4/13 11:14 下午
*/
@Controller
@RequestMapping("/cac/")
public class CaculatorController {
@Autowired
private CaculateHandler caculateHandler;
@RequestMapping("/test")
@ResponseBody
public String caculate() throws InterruptedException {
caculateHandler.caculate();
return "success";
}
}
启动类
@EnableAsync
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
定时任务
- 注解
- 方法上加上注解@Scheduled
- 在类上加注解 @EnableScheduling
代码demo
/**
* @author echoqian
* @date 2020/4/13 10:30 下午
*/
@Component
@EnableScheduling
public class SayHello {
// 开启一个异步任务
@Async
@Scheduled(cron = "0/1 * * * * *")
public void SayHello() throws InterruptedException {
System.out.println("hello");
}
}
查看Scheduled的源码
public @interface Scheduled {
String CRON_DISABLED = "-";
// 支持cron表达式
String cron() default "";
String zone() default "";
//以上一个任务的结束时间为基准 固定延时多久后执行
long fixedDelay() default -1L;
String fixedDelayString() default "";
// 以上一个任务的开始时间为基准 多少s执行一次
long fixedRate() default -1L;
String fixedRateString() default "";
long initialDelay() default -1L;
String initialDelayString() default "";
}
cron表达式不会的可以在线生成!