啟用定時任務
@SpringBootApplication
@EnableScheduling // 啟動類添加 @EnableScheduling 注解
public class ScheduleDemoApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduleDemoApplication.class, args);
}
}
新增定時任務類
@Component // 類上添加 @Component 注解
public class TaskDemo {
private static final Logger logger = LoggerFactory.getLogger(TaskDemo.class);
@Scheduled(cron = "0/5 * * * * ? ") // 方法上添加 @Scheduled 注解
public void job1(){
try {
logger.info("job1");
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Scheduled(cron = "0/5 * * * * ? ")
public void job2(){
try {
logger.info("job2");
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
多線程執行
從上面圖片可以看到開啟多個任務是以單線程執行的,執行完當前任務才會繼續執行下一個
啟用多線程執行有兩種方式:
使用默認線程池
@Component
@EnableAsync // 類上添加 @EnableAsync 注解
public class TaskDemo {
... ...
@Async // 方法上添加 @Async 注解
@Scheduled(cron = "0/5 * * * * ? ")
public void job1(){
... ...
}
... ...
}
使用自定義線程池
添加配置類:
@Configuration
public class SchedulerConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(2);
threadPoolTaskScheduler.setThreadNamePrefix("my-pool-");
threadPoolTaskScheduler.initialize();
scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
}
}
參考