异步任务和定时任务

目录

异步任务

1.创建一个异步任务

2.调用任务

3.开启异步任务注解——(无等待)

定时任务

1.了解定时任务的语法

2.定时任务举例

总结


异步任务

1.创建一个异步任务

public void hello() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理");
    }

2.调用任务

 @RequestMapping("/hello")
    public String hello() {
        asyncService.hello();//停止3秒
        return "Ok";
    }

3.开启异步任务注解——(无等待)

 @Async
    public void hello() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理");
    }

定时任务

引入:

taskExecutor   任务执行者
taskScheduler  任务调度者
@EnableScheduling     //开启定时注解功能
@Scheduled  //什么时候之行

1.了解定时任务的语法

@Scheduled(cron = "* * * * * *")

在一个特点的时间执行这个方法 ~ Timer

上图(cron = "* * * * * *")代表的含义为:

秒,分,时,日,月,周几~
    @Scheduled(cron = "0 * * * * ?")
    public void hello() {
        System.out.println("hello,你被执行了");
    }

2.定时任务举例

//每分钟的第一1秒执行一次
    @Scheduled(cron = "1 * * * * ?")
    public void hello() {
        System.out.println("hello,你被执行了");
    }
//每隔1秒执行一次
    @Scheduled(cron = "0/1 * * * * ?")
    public void hello() {
        System.out.println("hello,你被执行了");
    }
//每天10点15分30 执行一次
    @Scheduled(cron = "30 15 10 * * ? ")
    public void hello() {
        System.out.println("hello,你被执行了");
    }
//每天10点18点30秒,每隔5分钟执行一次
    @Scheduled(cron = "30 0/5 10,18 * * ?")
    public void hello() {
        System.out.println("hello,你被执行了");
    }

总结

  1. 定时任务,可以帮助我们做一些脚本,例如抢票——(合法)
  2. 定时任务,方便我们做一些计划,更准确
  3. 异步任务,使得我们的代码更快捷的运行
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值