Springboot整合定时任务和异步任务处理

一、定时任务

1.常用定时任务框架

说明
Java自带定时任务 Java自带的java.util.Timer
timer:配置比较麻烦,时间延后问题
timertask:不推荐
Quartz 配置相对于Java自带的更简单
SpringBoot自带定时任务 直接可以通过注解开启定时任务

2.使用Springboot自带的定时任务

步骤:

  1. 启动类添加 @EnableScheduling开启定时任务,自动扫描
  2. 定时任务业务类 加注解 @Component被容器扫描
  3. 定时执行的方法加上注解 @Scheduled定期执行

定时任务代码:

@Component
public class TestTask {
    @Scheduled(fixedRateString = "2000")
    public void test2() {
        System.out.println("结束 当前时间为:" + new Date());
    }
}

基于代码对定时任务属性的配置:

@Configuration
public class ScheduleConfig implements SchedulingConfigurer {

  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
      /**
       * 设置多个线程去执行 
       */
      taskRegistrar.setScheduler(
              Executors.newScheduledThreadPool(5));
  }
}

3.@Scheduled注解属性说明

说明
cron 定时任务表达式@Scheduled(cron="*/1 * * * * *")表示每秒
crontab 工具 https://tool.lu/crontab/
fixedRate 定时多久执行一次(上一次开始执行时间点后xx秒再次执行)
fixedDelay 上一次执行结束时间点后xx秒再次执行
fixedDelayString 字符串形式,可以通过配置文件指定,单位为毫秒

二、异步任务处理

相当于消息队列的功能,适用场景:日志记录,发送邮件、短信,支付,订单…

使用Springboot自带异步任务步骤:

  1. 启动类添加 @EnableAsync开启定时任务,自动扫描。
  2. 定义异步任务类并使用@Component标记组件被容器扫描,异步方法加上@Async
  3. controller层调用异步任务方法即可。

代码如下(@Async可作用于方法或类):

@Async
public class AsyncTask {
    public void task1() throws InterruptedException{
        long begin = System.currentTimeMillis();
        Thread.sleep(1000L);
        long end = System.currentTimeMillis();
        System.out.println("任务1耗时="+(end-begin));
    }
}
发布了81 篇原创文章 · 获赞 124 · 访问量 38万+

猜你喜欢

转载自blog.csdn.net/qq_38697437/article/details/104545576
今日推荐