Spring中@EnableScheduling實現(xiàn)定時任務(wù)代碼實例
@EnableScheduling實現(xiàn)定時任務(wù)

配置類
package com.lm.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @author Administrator
* @Configuration 主要用于標(biāo)記配置類,兼?zhèn)銫omponent的效果。
* @EnableScheduling 注解開啟定時任務(wù)功能。
*/
@Configuration
@EnableScheduling
public class ScheduleConfig {
}定時方法實現(xiàn)
可以將多個方法寫在一個類,也可以分多個類寫,當(dāng)然也可以將方法直接寫在上面ScheddulConfig類中
package com.lm.demo.task;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 要在任務(wù)的類上寫@Component,將當(dāng)前的任務(wù)類注入到容器
* 要在任務(wù)方法上寫@Scheduled,然后編寫cron表達(dá)式。
* @author Administrator
*/
@Component
public class SchedulingTask {
/**
* 表示每五秒執(zhí)行一次
*/
@Scheduled(cron = "*/5 * * * * ?")
public void testTask() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("執(zhí)行:"+dateFormat.format(new Date()));
}
/**
* 表示每3秒執(zhí)行一次
*/
@Scheduled(fixedDelay = 3*1000)
public void testTask2(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("執(zhí)行:"+dateFormat.format(new Date()));
}
}到此這篇關(guān)于Spring中@EnableScheduling實現(xiàn)定時任務(wù)代碼實例的文章就介紹到這了,更多相關(guān)@EnableScheduling實現(xiàn)定時任務(wù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Spring中的@EnableScheduling定時任務(wù)注解
- SpringBoot注解@EnableScheduling定時任務(wù)詳細(xì)解析
- SpringBoot使用Scheduling實現(xiàn)定時任務(wù)的示例代碼
- springboot通過SchedulingConfigurer實現(xiàn)多定時任務(wù)注冊及動態(tài)修改執(zhí)行周期(示例詳解)
- Spring定時任務(wù)關(guān)于@EnableScheduling的用法解析
- springboot項目使用SchedulingConfigurer實現(xiàn)多個定時任務(wù)的案例代碼
- SpringBoot使用SchedulingConfigurer實現(xiàn)多個定時任務(wù)多機器部署問題(推薦)
- Spring Scheduling本地任務(wù)調(diào)度設(shè)計與實現(xiàn)方式
相關(guān)文章
深入學(xué)習(xí)Java同步機制中的底層實現(xiàn)
在多線程編程中我們會遇到很多需要使用線程同步機制去解決的并發(fā)問題,這些同步機制是如何實現(xiàn)的呢?下面和小編來一起學(xué)習(xí)吧2019-05-05
基于SpringBoot和Vue3的博客平臺的用戶注冊與登錄功能實現(xiàn)
本教程將指導(dǎo)您如何使用Spring?Boot和Vue3實現(xiàn)用戶注冊與登錄功能。我們將使用Spring?Boot作為后端框架,Vue3作為前端框架,同時使用MySQL作為數(shù)據(jù)庫,感興趣的朋友可以參考一下2023-04-04
Gradle構(gòu)建Java項目指定JDK版本與編譯參數(shù)實戰(zhàn)演練
Gradle是一種流行的構(gòu)建工具,廣泛用于Java、Android和其他項目,通過配置環(huán)境變量,您可以更好地控制Gradle構(gòu)建過程,這篇文章主要介紹了Gradle構(gòu)建Java項目指定JDK版本與編譯參數(shù)的相關(guān)資料,需要的朋友可以參考下2026-04-04
Spring Boot 中的自動配置autoconfigure詳解
這篇文章主要介紹了Spring Boot 中的自動配置autoconfigure詳解,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-01-01
springboot+gradle 構(gòu)建多模塊項目的步驟
這篇文章主要介紹了springboot+gradle 構(gòu)建多模塊項目的步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05

