============================
============================
异步任务
如何在springboot中使用异步任务
在 SpringbootApplication
启动类上使用@EnableAsync
注解 开启异步任务
然后创建一个测试类AsyncService
@Async
@Service
public class AsyncService {
public void hello(){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("数据正在处理....");
}
}
测试调用
public String hello(){
asyncService.hello();//停止3秒
return "ok";
}
会发现会直接执行 return "ok";
异步任务总结:
@EnableAsync
开启异步任务
@Async
异步方法
定时执行任务
如何在springboot中使用定时任务
在 SpringbootApplication
启动类上使用@EnableScheduling
注解 开启任务调度
然后创建一个测试类ScheduledService
@Service
public class ScheduledService {
//在一个特定的时间执行这个方法 Timer
//cron 表达式~
//秒 分 时 日月 周几~
@Scheduled(cron = "0 23 16 * * ?") //?代表每
public void hello(){
System.out.println("hello 你被执行了");
}
}
注意 @Scheduled(cron = "0 23 16 * * ?")
这个注解内使用了cron
表达式
可以访问http://cron.qqe2.com/去在线生成表达式
定时任务总结:
TaskScheduler
任务调度者
TaskExecutor
任务执行者
@EnableScheduling
开启任务调度
@Scheduled
什么时候执行
关注我自建博客站
http://blog.petchk.cn/
关注我git博客https://chenhuakai.github.io/