启动时自动运行:
(1)实现CommandLineRunner接口;
(2)重写run()方法
import lombok.extern.slf4j.Slf4j; import org.springframework.boot.CommandLineRunner; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component @Slf4j public class Runner implements CommandLineRunner { @Override public void run(String... args) throws Exception { log.info("初始化run.........执行开始"); initResource(); log.info("初始化run.........执行结束"); } private void initResource(){ int sum = 0; for (int i = 0; i <= 100; i++) { sum += i; } log.info("结果为{}",sum); } }
如果有多个类实现了CommandLineRunner接口,需要指定其执行的顺序。采用@Order(value = 数值)来指定执行的顺序。其中数值越小越先执行。
当前两个类都实现了该接口
import lombok.extern.slf4j.Slf4j; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component @Slf4j @Order(value = 1) public class Runner implements CommandLineRunner { @Override public void run(String... args) throws Exception { log.info("初始化run.........执行开始"); initResource(); log.info("初始化run.........执行结束"); } private void initResource(){ int sum = 0; for (int i = 0; i <= 100; i++) { sum += i; } log.info("结果为{}",sum); } }
import lombok.extern.slf4j.Slf4j; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Slf4j @Order(value = 2) public class Runner_01 implements CommandLineRunner { @Override public void run(String... args) throws Exception { log.info(" Runner_01类代码.........执行开始"); } }
定时执行任务:
(1)在启动类开启定时任务@EnableScheduling
@SpringBootApplication //开启定时任务 @EnableScheduling public class DemoApplication { public static void main(String[] args) { ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args); } }
(2)@Scheduled(cron = " ")来指定自动执行规则
/** * 每分钟执行一次 */ @Scheduled(cron = "0 0/1 * * * ?") public void initResourcePool() { log.info("定时任务initResourcePool.........执行开始"); initResource(); log.info("定时任务initResourcePool.........执行结束"); }