springboot使用 @scheduled 多任务并发

springboot的@scheduled,并不是默认并发的,想给方法添加@Scheduled注解,实现两个定时任务。可是运行发现,两个task并没有并发执行,而是执行完一个task才会执行另外一个。

要 给类添加注解@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();
}
}
}
}

在这个类或启动类BootApplication添加@EnableScheduling标注

关注公众号“大模型全栈程序员”回复“小程序”获取1000个小程序打包源码。更多免费资源在http://www.gitweixin.com/?p=2627

发表评论

邮箱地址不会被公开。 必填项已用*标注