SpringBoot 定时任务(自定义线程池)

基于SpringBoot的定时任务配合自定义线程池实现,亲测可用;

第一步、创建线程池

 import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
/**
 * 线程池配置
 * @author zhh
 */
@Configuration
@EnableAsync // 该注解可以添加在启动类上面
public class ThreadPoolTaskConfig {
 
/** 
 *   默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,
 *	当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中;
 *  当队列满了,就继续创建线程,当线程数量大于等于maxPoolSize后,开始使用拒绝策略拒绝 
 */
	
	/** 核心线程数(默认线程数) */
	private static final int corePoolSize = 15;
	/** 最大线程数 */
	private static final int maxPoolSize = 50;
	/** 允许线程空闲时间(单位:默认为秒) */
	private static final int keepAliveTime = 60;
	/** 缓冲队列大小 */
	private static final int queueCapacity = 100;
	/** 线程名前缀 */
	private static final String threadNamePrefix = "Async-Service-";
	
	@Bean("taskExecutor") // bean的名称,默认为首字母小写的方法名
	public ThreadPoolTaskExecutor taskExecutor(){
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(corePoolSize);   
		executor.setMaxPoolSize(maxPoolSize);
		executor.setQueueCapacity(queueCapacity);
		executor.setKeepAliveSeconds(keepAliveTime);
		executor.setThreadNamePrefix(threadNamePrefix);
		
		// 线程池对拒绝任务的处理策略
        // CallerRunsPolicy:由调用线程(提交任务的线程)处理该任务
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		// 初始化
		executor.initialize();
		return executor;
	}
}

第二步、配置启动类

在启动类上添加注解 @EnableScheduling // 开启定时任务

@ServletComponentScan
@SpringBootApplication
@EnableScheduling // 开启定时任务
public class DemoApplication {
	public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

第三步、创建定时任务的类和方法

import java.text.SimpleDateFormat;
import java.util.Date;
 
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.scheduling.annotation.Async;
 
/**
 * Spring基于注解的定时任务类
 * @author zhaoheng
 */
@PropertySource(value = "classpath:task.properties")// 配置文件路径
@Component
public class SpringTaskController {
	private static final Logger logger = Logger.getLogger(SpringTaskController.class);
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    
    /**
      * 定时任务 2秒执行一次
      */
    private static final String times1 = "0/2 * * * * ?";  
 
   /**
     * 从配置文件读取参数
     */
        @Async // 异步执行,线程之间不会互相干扰
        @PostConstruct // 加上该注解项目启动时就执行一次该方法
	@Scheduled(cron = "${task.cron}") // cron表达式
	public void teskTestp() {
		System.out.println("定时任务teskTestp开始执行");
	}
 
    /**
     * 定时任务方法1
     */
        @Async // 异步执行,线程之间不会互相干扰,任务自动提交到线程池
        @PostConstruct // 加上该注解项目启动时就执行一次该方法
	@Scheduled(cron=times1)
	public void teskTest() {
	  
		//logger.info("定时任务开始执行。。。");
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(sdf.format(new Date())+"执行定时任务1执行");
		//logger.info("定时任务执行结束。。。");
	}

}

关于注解:

@EnableAsync 开启异步执行,添加到启动类或者配置上;
@Async 写在需要异步执行方法上,@Async("线程池名称"),可以通过设置参数指定使用哪个线程池,线程池名称为线程池的bean名称;

springBoot 已经为我们提供了线程池,如果我们不自定义线程池,在使用@Async注解的时候,会默认使用SpringBoot的默认线程池;当我们自定义线程的时候,线程池类型为ThreadPoolTaskExecutor ,就会使用我们自定义线程池;如果自定义线程池不是ThreadPoolTaskExecutor,可能需要指定线程池名称,例如:@Async("线程池名称"),否则还是会使用springBoot的默认线程池;

自定义一个ExecutorService类型的线程池,如下:当不指定线程池名称的时候,果然使用的是springBoot默认的线程池,而不是自定义的线程池;

SpringBoot 定时任务(自定义线程池)_第1张图片

 

如果不是SpringBoot的项目,可以参考这个:

https://blog.csdn.net/Muscleheng/article/details/80769884

你可能感兴趣的:(定时任务,Spring,task定时任务,SpringBoot,springBoot线程池,springBoot定时任务,Java定时任务,定时任务启动时执行,task)