1. 程式人生 > 其它 >springboot1學習(五)建立定時任務

springboot1學習(五)建立定時任務

技術標籤:springboot學習

使用@Scheduled註解

在Spring Boot的主類中加入@EnableScheduling註解,啟用定時任務的配置

新建schedule包,新建ScheduledTasks.java

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public
class ScheduledTasks { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); //Execute the annotated method with a fixed period between invocations. @Scheduled(fixedRate = 5000) public void reportCurrentTime() { //執行任務排程方法: System.out.
println("現在時間:" + dateFormat.format(new Date())); } }

測試結果
在這裡插入圖片描述

但是專案中一般不這麼用,分散式架構會產生冪等性問題,大專案都有專門的任務排程平臺

其次函式執行失敗沒有容錯機制