springboot定時任務@Scheduled

drawbackcc發表於2020-12-15

1.多個任務單執行緒執行(預設)

@Component 
@EnableScheduling   // 開啟定時任務,(這個註解用在啟動類上的話,就不用每個task類都寫一句@EnableScheduling
public class Task {

    @Scheduled(cron = "0/60 * * * * ?")//60s執行一次
    private void task1(){
        System.out.println("定時任務一,恭喜發財~" + LocalDateTime.now().toLocalTime() + "," + Thread.currentThread().getName());
    }

    @Scheduled(cron = "0/60 * * * * ?")//60s執行一次
    private void task2(){
        System.out.println("定時任務二,恭喜發財~" + LocalDateTime.now().toLocalTime() + "," + Thread.currentThread().getName());
    }
}

2.多執行緒非同步執行(註解@Async

@Component
@EnableScheduling
@EnableAsync        // 開啟多執行緒
public class Task {

    @Async
    @Scheduled(cron = "0/30 * * * * ?")
    public void task1(){
        System.out.println("定時任務一,恭喜發財~" + LocalDateTime.now().toLocalTime() + "," + Thread.currentThread().getName());
    }

    @Async
    @Scheduled(cron = "0/30 * * * * ?")
    public void task2(){
        System.out.println("定時任務二,恭喜發財~" + LocalDateTime.now().toLocalTime() + "," + Thread.currentThread().getName());
    }
}

在類上加註解@EnableAsync,然後在任務方法上加註解@Async

執行之後,發現就兩個任務,執行著執行著幾分鐘後執行緒數有一百多個了,又改成下面這樣

3.設定非同步執行執行緒池

程式碼和2一樣,多寫一個配置類

@Configuration
public class TaskPoolConfig {

    //定義執行緒池
    @Bean("taskExecutor")
    public Executor taskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setThreadNamePrefix("taskExecutorXXX-");
        //還有很多屬性可以設定
        return executor;
    }
}

寫完配置類後在@Async註解中指定執行緒池名即可,@Async("taskExecutor")(但是我發現不寫也行……)

其它,還有動態設定定時任務的寫法,以後補充……

 

相關文章