博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springboot + @scheduled 多任务并发
阅读量:7053 次
发布时间:2019-06-28

本文共 2087 字,大约阅读时间需要 6 分钟。

hot3.png

下面讲的是springboot + @scheduled 多任务并发,spring的定时任务(包括多任务并发)详解参见 

一、问题

项目采用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@EnableSchedulingpublic 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();             }         }     }}

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

二、解决

@Component@Configurable@EnableScheduling@EnableAsyncpublic 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();             }         }     }}

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

 

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

三、参考资料:

转载于:https://my.oschina.net/dong706/blog/1789053

你可能感兴趣的文章
Java 验证用户名、密码
查看>>
hdoj1010 奇偶剪枝+DFS
查看>>
doxygen
查看>>
iOS关于XML解析请求数据
查看>>
scrapy
查看>>
views 视图函数
查看>>
MySql详解(一)
查看>>
解题思路:蓄水池问题
查看>>
python网页分析
查看>>
总结 FileInputStream 与 FileOutputStream. BufferedInputStream 与 BufferedOutputStream .
查看>>
微信公众平台消息接口开发(8)小黄鸡(小贱鸡)机器人
查看>>
android 实时显示系统时间
查看>>
fatal error: asm/system.h: No such file or directory
查看>>
为什么要设计
查看>>
SerializableObj
查看>>
2018年5月31日笔记
查看>>
(转)CentOs上配置samba服务
查看>>
Photoshop给草坪上的人物加上唯美的紫色霞光
查看>>
移动平台对 META 标签的定义
查看>>
vim
查看>>