springboot 主动关闭项目(SpringBoot计划任务)(1)

3.3 计划任务

从 Spring 3.1 开始,计划任务在 Spring 中的实现变得异常的简单。首先通过在配置类注解 @EnableScheduling 来开启对计划任务的支持。 然后在要执行计划任务的方法上注解 @Scheduled ,声明这是一个计划任务。

Spring 通过 @Scheduled 可以支持多种类的计划任务,包含cron、fixDelay、fixRate 等。

/** * 定时任务 */ @Service @Slf4j public class ScheduledTaskService { /** * @Scheduled 声明该方法是计划任务,使用 fixedRate 属性每隔固定时间执行。 */ @Scheduled(fixedRate = 500) public void printRateDateTime(){ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); log.info("rate[500]: {}", LocalDateTime.now().format(formatter)); } /** * @Scheduled 声明该方法是计划任务,使用 fixedDelay 属性延迟固定时间执行。 */ @Scheduled(fixedDelay = 1000) public void printDelayDateTime(){ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); log.info("delay[1000]: {}", LocalDateTime.now().format(formatter)); } /** * @Scheduled 声明该方法是计划任务,使用 cron 属性可按照指定时间执行。 * cron 是UNIX 或 类 UNIX(Linux)系统下的定时任务 * 例子:每天 23:25 执行, 如果时间是过去时,不再执行。 */ @Scheduled(cron = "0 33 23 * * ?") public void printCronDateTime(){ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); log.info("cron[0 33 23 ?* *]: {}", LocalDateTime.now().format(formatter)); } } /** * 配置类 */ @Configuration @ComponentScan("chapter3.Scheduled") @EnableScheduling public class ScheduledTaskConfig{ } /** * 运行类 */ public class Run { public static void main(String[] args) { new AnnotationConfigApplicationContext(ScheduledTaskConfig.class); // 输出 // delay[1000]: 2019-07-07 23:32:57.878 // delay[1000]: 2019-07-07 23:32:58.884 // rate[500]: 2019-07-07 23:32:59.325 // rate[500]: 2019-07-07 23:32:59.827 // cron[0 33 23 ?* *]: 2019-07-07 23:33:00.003 // ...... } }

,