springboot集成 异步任务与定时执行任务

异步任务
在主程序开启异步

@EnableAsync

异步测试类

@Service
public class AsyncService {
    //告诉spring这是一个异步的方法
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理");
    }
}

controller

@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;


    @RequestMapping("/hello")
    public String hello(){//停止三秒
        asyncService.hello();
        return "ok";

    }
}

如果hello方法不加@Async注解的话页面就会等三秒在输出ok 如果有这个铸就就会知道这是一个异步任务就会开启多线程

定时执行

在程序入口开启定时

@EnableScheduling//开启定时功能的注解

在方法上加@Scheduled用cron表达式

@Service
public class ScheduledService {
    //在一个特定的时间执行这个方法
    //cron表达式
    //秒 分 时 日 月 周几
    //每天21点49分50秒生成 ?的意思是无论你写什么都是无效的
    //比如 13 13 14 20 * ? 不用管20号是星期几
    @Scheduled(cron = "40 57 21 * * *")
    public void hello(){
        System.out.println("你被捕了哈哈哈哈哈哈·1");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值