zoukankan      html  css  js  c++  java
  • springboot + @scheduled 多任务并发

    一、问题

    项目采用springboot搭建,想给方法添加@Scheduled注解,实现两个定时任务。可是运行发现,两个task并没有并发执行,而是执行完一个task才会执行另外一个。上代码:

    package com.autohome.contentplatform.tasks;
     
    import org.springframework.beans.factory.annotation.Configurable;
    import org.springframework.scheduling.annotation.EnableScheduling;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
     
    @Component
    @Configurable
    @EnableScheduling
    public class task1 {
         @Scheduled(cron = "0/5 * *  * * ? ")
         public void startSchedule() {
             System.out.println("===========1=>");
             try {
                 for(int i=1;i<=10;i++){
                     System.out.println("=1==>"+i);
                     Thread.sleep(1000);
                 }
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
         @Scheduled(cron = "0/5 * *  * * ? ")
         public void startSchedule2() {
             for(int i=1;i<=10;i++){
                 System.out.println("=2==>"+i);
                 try {
                     Thread.sleep(1000);
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
             }
         }
    }

    运行发现任务没有并行执行。

    二、解决

    给类添加注解@EnableAsync,并给方法添加注解@Async。

    @Component
    @Configurable
    @EnableScheduling
    @EnableAsync
    public class DemoTask {
         @Async
         @Scheduled(cron = "0/5 * *  * * ? ")
         public void startSchedule() {
             System.out.println("===========1=>");
             try {
                 for(int i=1;i<=10;i++){
                     System.out.println("=1==>"+i);
                     Thread.sleep(1000);
                 }
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
     
        @Async
         @Scheduled(cron = "0/5 * *  * * ? ")
         public void startSchedule2() {
             for(int i=1;i<=10;i++){
                 System.out.println("=2==>"+i);
                 try {
                     Thread.sleep(1000);
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
             }
         }
    }

    再次运行,发现两个任务可以并发执行了。

    三、参考资料:

    https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html

  • 相关阅读:
    经典回溯问题--八皇后dfs递归回溯求解【DFS】
    CSP认证考试(第九次)第一题
    C++字符串和数字格式转化(使用sprintf()和sscanf()函数)
    2016蓝桥杯C++A组第六题 寒假作业【暴力搜索】
    先序非递归建立二叉树
    sqlsrv数据库复杂语句1
    tp5域名配置
    JavaScript使用 value 属性
    数据库随机查询6条数据
    文件目录问题
  • 原文地址:https://www.cnblogs.com/shamo89/p/8341400.html
Copyright © 2011-2022 走看看