spring Boot 線程池異步執行多個定時任務

 1、自定義線性池

package com.sky.webpro.task;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executors;
//配置自定義線程池
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
//    @Override
//    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
//        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(5));
//    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(this.getTaskScheduler());
    }

    private ThreadPoolTaskScheduler getTaskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(5);
        taskScheduler.setThreadNamePrefix("schedule-pool-");
        taskScheduler.afterPropertiesSet();
        return taskScheduler;
    }

}

 2、定義job

package com.sky.webpro.task;

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

import java.time.LocalDateTime;

//@Component註解用於對那些比較中立的類進行註釋;
//相對與在持久層、業務層和控制層分別採用 @Repository、@Service 和 @Controller 對分層中的類進行註釋
@Component
@EnableScheduling   // 1.開啓定時任務
@EnableAsync        // 2.開啓多線程
public class MultithreadScheduleTask {

    @Async
    @Scheduled(fixedDelay = 1000)  //間隔1秒
    public void first() throws InterruptedException {
        System.out.println("第一個定時任務開始 : " + LocalDateTime.now().toLocalTime() + "\r\n線程 : " + Thread.currentThread().getName());
        System.out.println();
        Thread.sleep(1000 * 10);
    }

    @Async
    @Scheduled(fixedDelay = 2000)
    public void second() {
        System.out.println("第二個定時任務開始 : " + LocalDateTime.now().toLocalTime() + "\r\n線程 : " + Thread.currentThread().getName());
        System.out.println();
    }
}

或者:

SpringBoot開啓異步任務只需要兩步配置:

1、在主類上加上註解@EnableAsync開啓異步功能

2、在方法上加上註解@Async指定調用方法時是異步的

SpringBoot開啓定時任務也只需兩步配置:

1、在主類上加上註解@EnableScheduling開啓定時功能

2、在s方法上@Scheduled(cron = "0/5 * * * * MON-SAT")指定定時調用該方法

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