springboot 定時任務(多線程)


直接上代碼:

1、定義一個配置類

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
public class ScheduleConfig {

    @Value("${schedule.corePoolSize}")  // 引入yml配置
    private int corePoolSize;
    @Value("${schedule.maxPoolSize}")
    private int maxPoolSize;
    @Value("${schedule.queueCapacity}")
    private int queueCapacity;

    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.initialize();
        return executor;
    }

}

application.yml

schedule:
  corePoolSize: 10
  maxPoolSize: 100
  queueCapacity: 10

2、定義需要按時執行的服務

corn語句在線生成器:http://cron.qqe2.com/

說明:可能會遇到定時任務一下次執行多次的情況,這是由於執行速度很快,corn語句匹配仍然生效導致的。需要修改corn語句,使其精確匹配,比如在秒位置寫入0就是這個目的。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@EnableScheduling
public class ScheduleService {

    // 每10分鍾調用一次
    @Scheduled(cron = "0 0/10 * * * ?")  // corn語句
    @Async
    public void s1() {
        // 服務1
    }

    // 每天4點調用一次
    @Scheduled(cron = "0 0 4 * * ?")
    @Async
    public void s2() {
        // 服務2
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM