在项目过程中经常会用到spring的Schedule定时任务
然后Schedule定时任务默认是单线程的,在项目过程中就会出现比较耗时的任务跟比较频繁的任务冲突问题,

单线程情况下,例如8:00有一个耗时大约10分钟的定时任务,还有一个每一分钟一次的定时任务,那么8:00任务开始时,一分钟的任务就已经进入排队序列,并不执行

故而需要配置多线程的定时任务配置

配置文件: 

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

 
@Configuration
@EnableScheduling
@Slf4j
public class ScheduleConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
       //注册最大线程池100
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(Integer.MAX_VALUE));

//        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
//        scheduler.setPoolSize(8);
//        scheduler.setThreadNamePrefix("task-");
//        scheduler.setAwaitTerminationSeconds(60);
//        scheduler.setWaitForTasksToCompleteOnShutdown(true);
//        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(100,scheduler));
    }
//    @Async
//    @Scheduled(cron = "0/5 * * * * ?")
    public void time5() throws Exception {
        Thread.sleep(10000);
        log.info("0/5 * * * * ?");
    }
//    @Async
    @Scheduled(cron = "0/9 * * * * ?")
    public void time9() throws Exception {
        Thread.sleep(10000);
        log.info("0/9 * * * * ?");
    }
}

@Async 异步执行
被@Async标注过的方法不是在主线程中执行,是另开了一个线程,并且进行调度,从打印就可以看出,调度是随机的!

@Scheduled(cron = "0/9 * * * * ?")
被@Scheduled标注过的函数会按照配置的运行方式自动执行!此处配置的是cron = "0/9 * * * * ?"含义是每隔9s执行一次(在上次执行完后开始计时9s)

更多推荐

定时任务Schedule多线程配置