SpringBoot定時任務使用@EnableScheduling和@Scheduled這兩個註解就可以簡單實現,在集羣環境下建議用Quartz等實現。
很少說看代碼具體實現java
@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.0git
GitHub源碼github