相关阅读

@EnableScheduling

  1. <a name="VaJ3R"></a>
  2. ## 添加 Scheduled
  3. [示例代码](https://github.com/anydong/example-spring-boot/blob/master/src/main/java/com/anydong/example/springboot/task/LogTask.java)
  4. ```java
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.scheduling.annotation.Scheduled;
  8. import org.springframework.stereotype.Component;
  9. import java.util.Date;
  10. /**
  11. * @author anydong
  12. */
  13. @Component
  14. public class LogTask {
  15. private static final Logger LOGGER = LoggerFactory.getLogger(LogTask.class);
  16. @Scheduled(fixedDelay = 10000)
  17. public void printDatetime() {
  18. LOGGER.info((new Date()).toString());
  19. }
  20. }

并行运行多个任务

示例代码

  1. import org.springframework.context.annotation.Configuration;
  2. import org.springframework.scheduling.annotation.EnableScheduling;
  3. import org.springframework.scheduling.annotation.SchedulingConfigurer;
  4. import org.springframework.scheduling.config.ScheduledTaskRegistrar;
  5. import java.util.concurrent.Executors;
  6. import java.util.concurrent.ScheduledThreadPoolExecutor;
  7. import java.util.concurrent.ThreadPoolExecutor;
  8. /**
  9. * @author anydong
  10. */
  11. @Configuration
  12. @EnableScheduling
  13. public class SchedulingConfigurerImpl implements SchedulingConfigurer {
  14. @Override
  15. public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
  16. ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(3,
  17. Executors.defaultThreadFactory(),
  18. new ThreadPoolExecutor.AbortPolicy());
  19. scheduledTaskRegistrar.setScheduler(executor);
  20. }
  21. }