一分钟学会系列:定时任务实现方案

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/t1g2q3/article/details/88283547
  • Spring Task
    • 简单,使用注解,单线程,可配置多线程执行。
      @Slf4j
      @Component
      public class ScheduledService {
          @Scheduled(cron = "0/5 * * * * *")
          public void scheduled(){
              log.info("=====>>>>>使用cron  {}",System.currentTimeMillis());
          }
          @Scheduled(fixedRate = 5000)
          public void scheduled1() {
              log.info("=====>>>>>使用fixedRate{}", System.currentTimeMillis());
          }
          @Scheduled(fixedDelay = 5000)
          public void scheduled2() {
              log.info("=====>>>>>fixedDelay{}",System.currentTimeMillis());
          }
      }
      // 在主类上使用@EnableScheduling注解开启对定时任务的支持,然后启动项目。
      @Configuration
      @EnableAsync
      public class AsyncConfig {
          private int corePoolSize = 10;
          private int maxPoolSize = 200;
          private int queueCapacity = 10;
          @Bean
          public Executor taskExecutor() {
              ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
              executor.setCorePoolSize(corePoolSize);
              executor.setMaxPoolSize(maxPoolSize);
              executor.setQueueCapacity(queueCapacity);
              executor.initialize();
              return executor;
          }
      }
      
      // 然后在定时任务的类或者方法上添加@Async 。最后重启项目,每一个任务都是在不同的线程中。
  • spring-boot-starter-quartz
    • spring boot 2.0之后提供starter。
      public class TestQuartz extends QuartzJobBean {
          /**
           * 任务类需要执行QuartzJobBean
           * @param jobExecutionContext
           * @throws JobExecutionException
           */
          @Override
          protected void executeInternal(JobExecutionContext jobExecutionContext) 
              throws JobExecutionException {
              System.out.println("quartz task "+new Date());
          }
      }
      @Configuration
      public class QuartzConfig {
          @Bean
          public JobDetail teatQuartzDetail(){
              return JobBuilder.newJob(TestQuartz.class)
                               .withIdentity("testQuartz").storeDurably().build();
          }
      
          @Bean
          public Trigger testQuartzTrigger(){
              SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                      .withIntervalInSeconds(10)  //设置时间周期单位秒
                      .repeatForever();
              return TriggerBuilder.newTrigger().forJob(teatQuartzDetail())
                      .withIdentity("testQuartz")
                      .withSchedule(scheduleBuilder)
                      .build();
          }
      }
  •  niubi-job
    • 基于zookeeper实现的分布式任务调度框架,可以随时上传任务包。
  • xxl-job
    • 轻量级分布式任务调度平台,完善的告警机制。

猜你喜欢

转载自blog.csdn.net/t1g2q3/article/details/88283547