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("定时任务执行结束。。。");
	}

}

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

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章