异步任务&定时任务

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表达式不会的可以在线生成!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值