• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
敬YES
Now Or Never
博客园    首页       联系   管理    订阅  订阅
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

 


本人公众号[敬YES] 分享技术心得,欢迎关注~

如果文章对您有帮助,赞赏是对博主的支持

作者:陈敬(公众号:敬YES)
出处:http://www.cnblogs.com/janes/
博客文章仅供交流学习,请勿用于商业用途。如需转载,请务必注明出处。

posted on 2017-12-22 13:49  敬YES  阅读(18022)  评论(3)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3