spring boot--定时任务,线程池执行定时任务,启动成功后运行任务

  • spring boot启动成功之后执行代码

  1. 写一个类实现ApplicationRunner或CommandLineRunner接口,这两个接口除了传入参数不一样外,其他都一样。
  2. 放入spring IOC容器
@Component
public class MyApplicationRunnerDemo implements ApplicationRunner {
    private static final Logger log= LoggerFactory.getLogger(MyApplicationRunnerDemo.class);
    public void run(ApplicationArguments args) throws Exception {
        log.debug("MyApplicationRunnerDemo started.");
    }
}
@Component
public class MyCommandLineRunnerDemo implements CommandLineRunner {
    private static final Logger log= LoggerFactory.getLogger(MyCommandLineRunnerDemo.class);
    public void run(String... args) throws Exception {
        log.debug("MyCommandLineRunnerDemo started.");
    }
}

 

  • spring boot执行定时任务

  1. 在启动类上 加注解:@EnableScheduling
  2. 写一个类,在需要执行的方法上加注解@Scheduled(cron表达式)
  3. 放入spring IOC容器
@SpringBootApplication
@EnableScheduling
public class MainApp {
    public static void main(String[] args) {
        SpringApplication.run(MainApp.class,args);
    }
}
@Component
public class MySchedul {
    private static final Logger log= LoggerFactory.getLogger(MySchedul.class);

    @Scheduled(cron = "*/3 * * * * ?")
    public void job1(){
        log.debug("job1 stared");
    }

    @Scheduled(cron = "*/5 * * * * ?")
    public void job2(){
        log.debug("job2 stared");
    }
}

 

  • 线程池执行定时任务

  1. 配置线程池:@Bean("executor")
  2. 在启动类上 加注解:@EnableAsync
  3. 在定时任务方法上加注解:@Async("executor")
@Configuration
public class MyExecutor {

    @Bean("executor")
    public Executor executor(){
        ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();
        //核心线程数
        executor.setCorePoolSize(8);
        //最大核心线程数
        executor.setMaxPoolSize(16);
        //队列中等待被调度的任务数
        executor.setQueueCapacity(8);
        //
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        return executor;
    }
}
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class MainApp {
    public static void main(String[] args) {
        SpringApplication.run(MainApp.class,args);
    }
}
@Component
public class MySchedul {
    private static final Logger log= LoggerFactory.getLogger(MySchedul.class);

    @Scheduled(cron = "*/3 * * * * ?")
    @Async("executor")
    public void job1(){
        log.debug("job1 stared");
    }

    @Scheduled(cron = "*/5 * * * * ?")
    @Async("executor")
    public void job2(){
        log.debug("job2 stared");
    }
}

查看输出日志是否为同一个线程,如果不是,则配置成功:

spring boot--定时任务,线程池执行定时任务,启动成功后运行任务_第1张图片

你可能感兴趣的:(springboot,spring,boot,starter,Spring,Boot)