基於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的項目,可以參考這個: