1. 程式人生 > >SpringBoot使用非同步定時任務方法(一)

SpringBoot使用非同步定時任務方法(一)

簡單配置

1. 不用匯入其他依賴,只需要在啟動類上加入@EnableScheduling註解,啟動對定時任務的支援
2. 編寫非同步任務配置類,使用@EnableAsync啟用對非同步任務的支援,@Configuration表示該類為配置類
3. 具體類

@Configuration
@EnableAsync
public class AsyncTaskConfig {

    @Value("${task.async.pool.corePoolSize}")
    int corePoolSize;
    @Value("${task.async.pool.maxPoolSize}"
) int maxPoolSize; @Value("${task.async.pool.queueCapacity}") int queueCapacity; @Bean public Executor taskExecutor(){ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.initialize(); return
executor; } }

關於配置檔案資訊

#非同步任務執行緒池配置
task.async.pool.corePoolSize=10
task.async.pool.maxPoolSize=200
task.async.pool.queueCapacity=10

4. 建立任務類

@Component
public class AsyncTaskDemo {

    @Async
    @Scheduled(cron = "0/2 * * * * *")
    public void task(){
        System.out.println(this.hashCode());
    }
}