springboot中如何使用@Scheduled實現定時任務,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
成都創新互聯公司堅持“要么做到,要么別承諾”的工作理念,服務領域包括:網站設計制作、成都做網站、企業官網、英文網站、手機端網站、網站推廣等服務,滿足客戶于互聯網時代的羅定網站設計、移動媒體設計的需求,幫助企業找到有效的互聯網解決方案。努力成為您成熟可靠的網絡建設合作伙伴!1、pom.xml中導入必要的依賴:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </parent> <dependencies> <!-- SpringBoot 核心組件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> </dependencies>
2、寫一個springboot的啟動類:
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.context.annotation.ComponentScan;import org.springframework.scheduling.annotation.EnableScheduling;@ComponentScan(basePackages = { "com.xwj.tasks" })@EnableScheduling // 開啟定時任務@EnableAutoConfigurationpublic class App { public static void main(String[] args) { SpringApplication.run(App.class, args); }}
注意這里一定要加上@EnableScheduling注解,用于開啟定時任務
3、開始寫定時任務:
import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;@Componentpublic class ScheduleTask { @Scheduled(fixedRate = 1000) // @Scheduled(cron = "0 23-25 18 * * ?") public void testSchedule() { System.out.println("定時任務:" + System.currentTimeMillis()); }}
解釋:
@Scheduled注解:
1、fixedRate 以固定速率執行。以上表示每隔1秒執行一次
2、fixedDelay 以上一個任務開始時間為基準,從上一任務開始執行后再次調用
3、cron表達式。可以實現定時調用。
在使用的過程中,樓主覺得,如果只有一個定時任務,fixedRate與fixedDelay的效果是一樣一樣的
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注創新互聯行業資訊頻道,感謝您對創新互聯網站建設公司,的支持。
網站題目:springboot中如何使用@Scheduled實現定時任務-創新互聯
標題路徑:http://vcdvsql.cn/article14/ddjgge.html
成都網站建設公司_創新互聯,為您提供ChatGPT、手機網站建設、網頁設計公司、域名注冊、云服務器、定制網站
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯