15、Springboot的异步任务和定时执行任务

============================
\color{#4285f4}{K}\color{#ea4335}{a}\color{#fbbc05}{r}\color{#4285f4}{y}\color{#34a853}{开}\color{#ea4335}{源}
============================

异步任务

如何在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/

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容