SpringBoot定時任務使用@EnableScheduling和@Scheduled這兩個註解就可以簡單實現,在集羣環境下建議用Quartz等實現。java
很少說看代碼具體實現git
@Configuration @EnableScheduling public class ScheduledConfig { }
@Service public class ScheduleService { @Scheduled(fixedDelay = 2000) public void scheduleTest1() throws InterruptedException { System.out.println("scheduleTest1 Start.>>" + new Date().toLocaleString()); Thread.sleep(6000); System.out.println("scheduleTest1 End.>>" + new Date().toLocaleString()); } @Scheduled(fixedRate = 2000) public void scheduleTest2() throws InterruptedException { System.out.println("scheduleTest2 Start.>>" + new Date().toLocaleString()); Thread.sleep(6000); System.out.println("scheduleTest2 End.>>"); } @Scheduled(cron = "0 0/1 * * * ? ") public void scheduleTest3() { System.out.println("scheduleTest3 >>>"); } @Scheduled(fixedRate = 2000, initialDelay = 1000) public void scheduleTest4() throws InterruptedException { System.out.println("scheduleTest2 fixedRate Start.>>"); Thread.sleep(6000); System.out.println("scheduleTest2 fixedRate End.>>"); } }
@Bean public ScheduledExecutorService scheduledExecutorService() { return new ScheduledThreadPoolExecutor(10); }
@Bean public TaskScheduler taskScheduler() { ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler(); threadPoolTaskScheduler.setPoolSize(20); return threadPoolTaskScheduler; }
@Configuration @EnableScheduling public class ScheduledConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(taskExecutor()); } @Bean(destroyMethod = "shutdown") public Executor taskExecutor() { return Executors.newScheduledThreadPool(20); } }
【注】代碼基於SpringBoot 2.0github
GitHub源碼spring