@SpringBootApplication
@EnableScheduling // 启动类添加 @EnableScheduling 注解
public class ScheduleDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(ScheduleDemoApplication.class, args);
    }

}

新增定时任务类

@Component // 类上添加 @Component 注解
public class TaskDemo {

    private static final Logger logger = LoggerFactory.getLogger(TaskDemo.class);

    @Scheduled(cron = "0/5 * * * * ? ") // 方法上添加 @Scheduled 注解
    public void job1(){
        try {
            logger.info("job1");
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Scheduled(cron = "0/5 * * * * ? ")
    public void job2(){
        try {
            logger.info("job2");
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Spring Boot 内置定时任务

多线程执行

从上面图片可以看到开启多个任务是以单线程执行的,执行完当前任务才会继续执行下一个

启用多线程执行有两种方式:

使用默认线程池

@Component
@EnableAsync // 类上添加 @EnableAsync 注解
public class TaskDemo {

    ... ...

    @Async // 方法上添加 @Async 注解
    @Scheduled(cron = "0/5 * * * * ? ")
    public void job1(){
        ... ...
    }

    ... ...
}

Spring Boot 内置定时任务

使用自定义线程池

添加配置类:

@Configuration
public class SchedulerConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

        threadPoolTaskScheduler.setPoolSize(2);
        threadPoolTaskScheduler.setThreadNamePrefix("my-pool-");
        threadPoolTaskScheduler.initialize();

        scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
    }
}

Spring Boot 内置定时任务

参考

相关文章:

  • 2021-08-07
  • 2022-12-23
  • 2022-12-23
  • 2021-05-25
  • 2021-09-29
猜你喜欢
  • 2021-07-23
  • 2021-10-09
  • 2022-12-23
  • 2022-12-23
  • 2021-08-17
  • 2021-12-11
相关资源
相似解决方案