Java Scheduled定时任务(二)——开启多线程定时任务

35 篇文章 2 订阅

我们在Java Scheduled定时任务中已经学到了如何开启定时任务,但却在同时开启多个定时任务的时候,遇到了新的问题,Scheduled定时任务是单线程的,无法满足同一个时间开启多个定时任务,因此,我们进行了如下调整:

1、新建一个配置类;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
@EnableAsync

public class AsyncConfig {

    private int corePoolSize = 10;
    private int maxPoolSize = 200;
    private int queueCapacity = 10;

    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.initialize();
        return executor;
    }
}

2、在定时任务中添加@Async异步注解,即可开启多线程定时任务。

但通过如上方法,又会出现新的问题,如果某个定时任务在规格的时间内没有运行完,而它新的定时任务再次开启,就会出现两个定时任务同时对表的数据进行操作,会导致数据各种的错误,因此,再次对定时任务进行处理,增加锁机制(synchronized),对未执行完的定时任务及时锁住,不让它开启下一个定时任务。

实例如下所示:

    private static Object lkm1 = new Object();

    private static Object lkm2 = new Object();


    /**
    *
    * @description:
    * @author: lkm
    * @date: 2023/9/7 9:15
    **/
    @Scheduled(cron = "0 0/1 * * * ?")
    public void scheduledTask1() throws Exception {
        synchronized(lkm1){
            Date date =new Date();
            System.out.println("====================任务开始1=================");
            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
            Thread.sleep(120000);//2分钟
            System.out.println("====================任务1,结束=================");
        }
    }

    /**
    *
    * @description:
    * @author: lkm
    * @date: 2023/9/7 9:15
    **/
    @Scheduled(cron = "0 0/1 * * * ?")
    public void scheduledTask2() throws Exception {
        synchronized(lkm2){
            Date date =new Date();
            System.out.println("====================任务开始2=================");
            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
            Thread.sleep(120000);//2分钟
            System.out.println("====================任务2,结束=================");
        }
    }
  • 26
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

傻猴儿

小编,多谢客官留下的赏钱。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值