Springboot 中@Scheduled 定时任务实现多任务并发

在Springboot项目中,使用@Scheduled创建的定时任务默认顺序执行。为实现多任务并发,需要配合@EnableAsync和@Async注解。通过在类上添加@EnableAsync,在方法上添加@Async,使得方法调用异步执行,从而达到并发效果。官方文档对@Async的解释指出,这样注解的方法会在单独的任务中异步执行,调用者无需等待即可返回。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

场景:

项目采用springboot搭建,想给方法添加@Scheduled注解,实现两个定时任务。但两个定时任务没有并发执行,而是执行完一个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 sta
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值