tft每日頭條

 > 生活

 > springboot 主動關閉項目

springboot 主動關閉項目

生活 更新时间:2024-09-30 13:16:28

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 // ...... } }

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关生活资讯推荐

热门生活资讯推荐

网友关注

Copyright 2023-2024 - www.tftnews.com All Rights Reserved