-
spring boot启动成功之后执行代码
- 写一个类实现ApplicationRunner或CommandLineRunner接口,这两个接口除了传入参数不一样外,其他都一样。
- 放入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执行定时任务
- 在启动类上 加注解:@EnableScheduling
- 写一个类,在需要执行的方法上加注解@Scheduled(cron表达式)
- 放入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");
}
}
-
线程池执行定时任务
- 配置线程池:@Bean("executor")
- 在启动类上 加注解:@EnableAsync
- 在定时任务方法上加注解:@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");
}
}
查看输出日志是否为同一个线程,如果不是,则配置成功: