1.springBoot默认的定时任务为串行方式,即所有任务都只有一个线程在执行
代码示例:
springBoot启动类
@SpringBootApplication
@EnableScheduling /**开启定时任务*/
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
任务调度
@Component
public class MultiThreadTask {
private Logger logger = LoggerFactory.getLogger(MultiThreadTask.class);
@Scheduled(cron = "0/5 * * * * ?")
public void schedule1() throws Exception {
for (int i=0; i<10000; i++) {
logger.info("------------");
Thread.sleep(100);
}
}
@Scheduled(cron = "0/5 * * * * ?")
public void schedule2() throws Exception {
for (int i=0; i<10000; i++) {
logger.info("++++++++++++");
Thread.sleep(100);
}
}
}
执行结果
2.springBoot开启多线程定时任务
在1的基础上加上定时任务配置类
package com.gomeet.common.conf;
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;
@Configuration
@EnableScheduling
public class AsyncScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(taskExecutor());
}
@Bean
public Executor taskExecutor() {
return Executors.newScheduledThreadPool(20);
}
}
执行结果
如此便实现了springBoot定时任务的并行处理