springboot使用异步+定时任务 解决定时任务阻塞的问题


import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 定时任务:
 *      1.@EnableScheduling 开启定时任务
 *      2.@Scheduled 开启一个定时任务
 *      3.自动配置类:TaskSchedulingAutoConfiguration
 * <p>
 * 异步任务:
 *      1.@EnableAsync  开启异步任务功能
 *      2.@Async 给异步执行的方法标上该注解
 *      3.自动配置类:TaskExecutionAutoConfiguration
 */
@EnableScheduling
@EnableAsync
@Slf4j
@Component
public class HelloSchedule {

    /**
     * 1.在spring中6位组成  不能是7位
     * 2.在周几的位置  1-7 代表周一到周日
     * 3.定时任务不能阻塞  默认是阻塞的
     *          1)可以让业务运行以异步的方式  自己提交到线程池 --> CompletableFuture.runAsync()
     *          2) 支持定时任务线程池  设置TaskSchedulingProperties
     *              spring.task.scheduling.pool.size=5 有些版本不太管用。。
     *          3)定时任务异步执行
     *              异步任务:
     *
     *          解决:使用异步+定时任务解决定时任务阻塞的问题
     */
    @Scheduled(cron = "* * * ? * 7")
    @Async
    public void hello() {
        log.info("hello....");

        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }



    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值