Springboot整合定時排程
阿新 • • 發佈:2020-11-25
1、利用定時排程可以幫助使用者實現無人值守程式執行,在Spring中提供了簡單的SpringTask排程執行任務,利用此元件可以實現間隔排程與CRON排程處理。
首先需要建立一個執行緒排程類,如下所示:
1 package com.demo.cron; 2 3 import java.text.SimpleDateFormat; 4 import java.util.Date; 5 6 import org.springframework.scheduling.annotation.Scheduled; 7 import org.springframework.stereotype.Component;8 9 /** 10 * 11 * @author 12 * 13 */ 14 @Component 15 public class CronSchedulerTask { 16 17 /** 18 * 定義一個要執行的任務 19 */ 20 @Scheduled(fixedRate = 2000) // 採用間隔排程,每隔2秒執行一次 21 public void runJobA() { 22 System.err.println("【*** runJobA ***】 " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())); 23 } 24 25 /** 26 * 定義一個要執行的任務 27 */ 28 @Scheduled(cron = "* * * * * ?") // 採用間隔排程,每隔1秒執行一次 29 public void runJobB() { 30 System.err.println("【*** runJobB ***】 " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())); 31 } 32 33}
為了讓多個任務並行執行,還需要建立一個定時排程池的配置類,如下所示;
1 package com.demo.config; 2 3 import java.util.concurrent.Executors; 4 5 import org.springframework.context.annotation.Configuration; 6 import org.springframework.scheduling.annotation.SchedulingConfigurer; 7 import org.springframework.scheduling.config.ScheduledTaskRegistrar; 8 9 /** 10 * 定時排程的配置類一定要實現指定的父介面 11 * 12 * @author 13 * 14 */ 15 @Configuration 16 public class SchedulerConfig implements SchedulingConfigurer { 17 18 /** 19 * 開啟執行緒排程池 20 */ 21 @Override 22 public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { 23 // 10個執行緒池 24 taskRegistrar.setScheduler(Executors.newScheduledThreadPool(10)); 25 } 26 27 }
切記,要在程式啟動類上追加定時任務配置註解,如下所示:
1 package com.demo; 2 3 import org.springframework.boot.SpringApplication; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 import org.springframework.data.jpa.repository.config.EnableJpaRepositories; 6 import org.springframework.scheduling.annotation.EnableScheduling; 7 import org.springframework.transaction.annotation.EnableTransactionManagement; 8 9 @SpringBootApplication // 啟動Springboot程式,而後自帶子包掃描 10 @EnableScheduling // 啟動排程 11 public class DemoApplication { 12 13 public static void main(String[] args) { 14 // 啟動Springboot程式 15 SpringApplication.run(DemoApplication.class, args); 16 } 17 18 }
執行效果,如下所示: