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")(但是我发现不写也行……)
其它,还有动态设置定时任务的写法,以后补充……