spring boot使用线程池ThreadPoolTaskExecutor实现多线程执行定时任务

spring boot实现定时任务比较简单,基于注解(@Scheduled)就够了,只需几行代码便可完成。 代码如下:

package com.china.great.amos.chinagreatblog.thread;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @Author: Liu HongYang
 * @DateTime: 2020/5/19 12:46 下午
 * @Description: TODO
 */
@Component
@EnableScheduling
public class InsertJob {

    /**默认是fixedDelay 上一次执行完毕时间后执行下一轮*/
    @Scheduled(cron = "0/5 * * * * *")
    public void run() throws InterruptedException {
        //Thread.sleep(3000);
        System.out.println(Thread.currentThread().getName()+"=====>>>>>5秒使用cron  {}"+(System.currentTimeMillis()/1000));
    }


}

Cron表达式参数分别表示:

秒(0~59) 例如0/5表示每5秒
分(0~59)
时(0~23)
日(0~31)的某天,需计算
月(0~11)
周几( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
@Scheduled:除了支持灵活的参数表达式cron之外,还支持简单的延时操作,例如 fixedDelay ,fixedRate 填写相应的毫秒数即可。

到此定时任务的功能就完成了,此时,如果有多个任务呢,那就需要多个线程来执行了,需要配置线程池,上代码:

package com.china.great.amos.chinagreatblog.config;

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;

/**
 * @Author: Liu HongYang
 * @DateTime: 2020/5/20 10:36 上午
 * @Description: TODO
 */
@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;
    }
}

配置完毕,接着在刚刚的InsertJob类上面加上注解@Async,大功告成
,执行的结果如下图,都是不同的线程在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值