1 import java.text.SimpleDateFormat; 2 import java.util.Date; 3 4 import org.springframework.context.annotation.Configuration; 5 import org.springframework.scheduling.annotation.EnableScheduling; 6 import org.springframework.scheduling.annotation.Scheduled; 7 import org.springframework.stereotype.Component; 8 9 /** 10 * 測試spring定時任務執行 11 */ 12 @Component 13 @Configuration 14 @EnableScheduling 15 public class MyTestTask { 16 private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 17 18 @Scheduled(cron="* * * * * *") // 關於定時任務執行時間,後續會在別的文章中添加 19 public void executeUpdateYqTask() { 20 System.out.println(Thread.currentThread().getName() + " >>> task one " + format.format(new Date())); 21 } 22 23 @Scheduled(cron="* * * * * *") 24 public void executeRepaymentTask() throws InterruptedException { 25 System.out.println(Thread.currentThread().getName() + " >>> task two " + format.format(new Date())); 26 } 27 }
1 import java.util.concurrent.Executor; 2 3 import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; 4 import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler; 5 import org.springframework.context.annotation.Bean; 6 import org.springframework.context.annotation.Configuration; 7 import org.springframework.scheduling.TaskScheduler; 8 import org.springframework.scheduling.annotation.AsyncConfigurer; 9 import org.springframework.scheduling.annotation.EnableScheduling; 10 import org.springframework.scheduling.annotation.SchedulingConfigurer; 11 import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; 12 import org.springframework.scheduling.config.ScheduledTaskRegistrar; 13 14 @Configuration 15 @EnableScheduling 16 public class ScheduleConfig implements SchedulingConfigurer, AsyncConfigurer{ 17 18 /** 異步處理 */ 19 public void configureTasks(ScheduledTaskRegistrar taskRegistrar){ 20 TaskScheduler taskScheduler = taskScheduler(); 21 taskRegistrar.setTaskScheduler(taskScheduler); 22 } 23 24 /** 定時任務多線程處理 */ 25 @Bean(destroyMethod = "shutdown") 26 public ThreadPoolTaskScheduler taskScheduler(){ 27 ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); 28 scheduler.setPoolSize(20); 29 scheduler.setThreadNamePrefix("task-"); 30 scheduler.setAwaitTerminationSeconds(60); 31 scheduler.setWaitForTasksToCompleteOnShutdown(true); 32 return scheduler; 33 } 34 35 /** 異步處理 */ 36 public Executor getAsyncExecutor(){ 37 Executor executor = taskScheduler(); 38 return executor; 39 } 40 41 /** 異步處理 異常 */ 42 public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(){ 43 return new SimpleAsyncUncaughtExceptionHandler(); 44 } 45 }
最後:java
在啓動類加上 @EnableScheduling 就能夠了spring
1 /** 2 * 啓動類 3 */ 4 @SpringBootApplication 5 @EnableScheduling 6 public class AppApplication extends SpringBootServletInitializer {}