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");
    }
}

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

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值