使用Spring Task完成定時任務

1. 前言
上一篇我們學習了Quartz作為定時任務的框架的使用, 這一篇我們來學習Spring全家桶的SpringTask, 對于主張簡單易用的Spring家族來說, SpringTask無疑也是一個輕量級的框架,他比Quartz更容易上手.

2. pom.xml依賴
? <dependencies>
? ? <dependency>
? ? ? <groupId>org.springframework</groupId>
? ? ? <artifactId>spring-context</artifactId>
? ? ? <version>4.3.12.RELEASE</version>
? ? </dependency>
? ? <dependency>
? ? ? <groupId>org.springframework</groupId>
? ? ? <artifactId>spring-context-support</artifactId>
? ? ? <version>4.3.12.RELEASE</version>
? ? </dependency>
? ? <dependency>
? ? ? <groupId>junit</groupId>
? ? ? <artifactId>junit</artifactId>
? ? ? <version>4.12</version>
? ? </dependency>
? ? <dependency>
? ? ? <groupId>org.springframework</groupId>
? ? ? <artifactId>spring-test</artifactId>
? ? ? <version>4.3.12.RELEASE</version>
? ? </dependency>
? </dependencies>
?
對的,一個spring-context就是他所需要的框架了, 也就是說, 如果你現在開發的項目是用的spring ,無需管依賴,直接看下一步就可以了.

2. 實現代碼
spring 的老套路, 一般都可以用兩種方式實現: 一是配置方式,二是注解方式

2.1 基于xml配置文件的方式
1 . 寫一個運行任務的job類

package com.zgd.spring.task;

import java.util.Date;

/**
?* xml配置方式的定時任務
?*/
public class XmlTask {

? ? /**
? ? ?* 要執行的任務
? ? ?*/
? ? public void task(){
? ? ? ? System.out.println("定時任務執行中: "+new Date().toLocaleString());
? ? }
}
?
2 .在resource文件夾中, 創建spring 的配置文件: spring.xml , 這里特意要注意beans中的命名空間不能少

<beans xmlns="http://www.springframework.org/schema/beans"
? ? ? ?xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
? ? ? ?xmlns:task="http://www.springframework.org/schema/task"
? ? ? ?xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans
? http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
? http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">

<bean id="xmlTask" class="com.zgd.spring.task.XmlTask"/>
? ? <task:scheduled-tasks>
? ? ? ? <!--每5秒鐘運行一次-->
? ? ? ? <task:scheduled ref="xmlTask" method="task" cron="0/5 * * * * ?"/>
? ? </task:scheduled-tasks>
</beans>
?
關于cron的語法:?
Cron表達式是一個字符串,字符串以5或6個空格隔開,分為6或7個域,每一個域代表一個含義,Cron有如下兩種語法格式:

(1)Seconds ?Minutes ?Hours ?DayofMonth ?Month ?DayofWeek ?Year
(2)Seconds ?Minutes ?Hours ?DayofMonth ?Month ?DayofWeek

每一個域可出現的字符如下:?
Seconds:可出現", - * /"四個字符,有效范圍為0-59的整數?
Minutes:可出現", - * /"四個字符,有效范圍為0-59的整數?
Hours:可出現", - * /"四個字符,有效范圍為0-23的整數?
DayofMonth:可出現", - * / ? L W C"八個字符,有效范圍為1-31的整數?
Month:可出現", - * /"四個字符,有效范圍為1-12的整數或JAN-DEc ? ?
DayofWeek:可出現", - * / ? L C #"四個字符,有效范圍為1-7的整數或SUN-SAT兩個范圍。1表示星期天,2表示星期一, 依次類推?
Year:可出現", - * /"四個字符,有效范圍為1970-2099年
每一個域都使用數字,但還可以出現如下特殊字符,它們的含義是:?
(1)*:表示匹配該域的任意值,假如在Minutes域使用*, 即表示每分鐘都會觸發事件。
(2)?:只能用在DayofMonth和DayofWeek兩個域。它也匹配域的任意值,但實際不會。因為DayofMonth和 DayofWeek會相互影響。例如想在每月的20日觸發調度,不管20日到底是星期幾,則只能使用如下寫法: 13 13 15 20 * ?, 其中最后一位只能用?,而不能使用*,如果使用*表示不管星期幾都會觸發,實際上并不是這樣。?
(3)-:表示范圍,例如在Minutes域使用5-20,表示從5分到20分鐘每分鐘觸發一次?
(4)/:表示起始時間開始觸發,然后每隔固定時間觸發一次,例如在Minutes域使用5/20,則意味著5分鐘觸發一次,而25,45等分別觸發一次.?
(5),:表示列出枚舉值值。例如:在Minutes域使用5,20,則意味著在5和20分每分鐘觸發一次。?
(6)L:表示最后,只能出現在DayofWeek和DayofMonth域,如果在DayofWeek域使用5L,意味著在最后的一個星期四觸發。?
(7)W: 表示有效工作日(周一到周五),只能出現在DayofMonth域,系統將在離指定日期的最近的有效工作日觸發事件。例如:在 DayofMonth使用5W,如果5日是星期六,則將在最近的工作日:星期五,即4日觸發。如果5日是星期天,則在6日(周一)觸發;如果5日在星期一 到星期五中的一天,則就在5日觸發。另外一點,W的最近尋找不會跨過月份?
(8)LW:這兩個字符可以連用,表示在某個月最后一個工作日,即最后一個星期五。?
(9)#:用于確定每個月第幾個星期幾,只能出現在DayofMonth域。例如在4#2,表示某月的第二個星期三。
?
舉例如下:

?<!-- 每半分鐘觸發任務 -->
?<task:scheduled ref="app" method="execute1" cron="30 * * * * ?"/>
?<!-- 每小時的10分30秒觸發任務 -->
?<task:scheduled ref="app" method="execute2" cron="30 10 * * * ?"/>
?<!-- 每天1點10分30秒觸發任務 -->
?<task:scheduled ref="app" method="execute3" cron="30 10 1 * * ?"/>
?<!-- 每月20號的1點10分30秒觸發任務 -->
?<task:scheduled ref="app" method="execute4" cron="30 10 1 20 * ?"/>
?<!-- 每年10月20號的1點10分30秒觸發任務 -->
?<task:scheduled ref="app" method="execute5" cron="30 10 1 20 10 ?"/>
?<!-- 每15秒、30秒、45秒時觸發任務 -->
?<task:scheduled ref="app" method="execute6" cron="15,30,45 * * * * ?"/>
?<!-- 15秒到45秒每隔1秒觸發任務 -->
?<task:scheduled ref="app" method="execute7" cron="15-45 * * * * ?"/>
?<!-- 每分鐘的每15秒時任務任務,每隔5秒觸發一次 -->
?<task:scheduled ref="app" method="execute8" cron="15/5 * * * * ?"/>
?<!-- 每分鐘的15到30秒之間開始觸發,每隔5秒觸發一次 -->
?<task:scheduled ref="app" method="execute9" cron="15-30/5 * * * * ?"/>
?<!-- 每小時的0分0秒開始觸發,每隔3分鐘觸發一次 -->
?<task:scheduled ref="app" method="execute10" cron="0 0/3 * * * ?"/>
?<!-- 星期一到星期五的10點15分0秒觸發任務 -->
?<task:scheduled ref="app" method="execute11" cron="0 15 10 ? * MON-FRI"/>
?
然后我們需要一個測試類來測試:

package com.zgd.spring;


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring.xml")
public class App{

? ? @Test
? ? public void start(){
? ? ? ? System.out.println("啟動spring");
? ? ? ? while (true){
? ? ? ? ? ? //使用死循環確保程序持續的運行
? ? ? ? }
? ? }

}
?
運行結果:?


2.2 基于@Scheduled注解的方式
這個注解可以傳五個參數:

cron:指定cron表達式
zone:官方文檔解釋:A time zone for which the cron expression will be resolved。指定cron表達式運行的時區
fixedDelay:官方文檔解釋:An interval-based trigger where the interval is measured from the completion time of the previous task. The time unit value is measured in milliseconds.即表示從上一個任務完成開始到下一個任務開始的間隔,單位是毫秒。
fixedRate:官方文檔解釋:An interval-based trigger where the interval is measured from the start time of the previous task. The time unit value is measured in milliseconds.即從上一個任務開始到下一個任務開始的間隔,單位是毫秒。
initialDelay:官方文檔解釋:Number of milliseconds to delay before the first execution of a fixedRate() or fixedDelay() task.任務第一次被調用前的延時,單位毫秒?
再寫一個任務類:
package com.zgd.spring.task;

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

import java.util.Date;

/**
?* 注解執行的任務
?*/
@Component
public class AnnoTask {

? ? /**
? ? ?* 使用注解,5秒執行一次
? ? ?*/
? ? @Scheduled(cron = "0/5 * * * * ?")
? ? public void task(){
? ? ? ? System.out.println("注解的方式的任務執行了" + new Date().toLocaleString());
? ? }

}

?
2 . 在spring配置文件頭中添加命名空間及描述,并開啟定時任務注解驅動

<beans xmlns="http://www.springframework.org/schema/beans"
? ? ? ?xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
? ? ? ?xmlns:task="http://www.springframework.org/schema/task"
? ? ? ?xmlns:context="http://www.springframework.org/schema/context"
? ? ? ?xsi:schemaLocation="http://www.springframework.org/schema/beans
? http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
? http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

? ? <bean id="xmlTask" class="com.zgd.spring.task.XmlTask"/>

? ?<!-- <task:scheduled-tasks>
? ? ? ? &lt;!&ndash;每5秒鐘運行一次&ndash;&gt;
? ? ? ? <task:scheduled ref="xmlTask" method="task" cron="0/5 * * * * ?"/>
? ? </task:scheduled-tasks>-->
? ? <task:annotation-driven />

? ? <context:component-scan base-package="com.zgd.spring.task"/>

</beans>
?
這里我試了一下,怎么都無法執行定時任務, 后面仔細檢查,發現是沒有加上注解的自動掃描, 平時開發肯定都會加上這個,但是由于是測試demo所以把這個忘記了.?
<context:component-scan base-package="com.zgd.spring.task"/>

運行我們的測試類, 結果如下?

---------------------?
作者:zzzgd_666?
來源:CSDN?
原文:https://blog.csdn.net/zzzgd_666/article/details/80723654?
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/386919.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/386919.shtml
英文地址,請注明出處:http://en.pswp.cn/news/386919.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python 讀寫文件

https://www.cnblogs.com/evablogs/p/6725242.html 文件的打開讀寫關閉&#xff08;文件使用完畢后必須關閉&#xff0c;因為文件對象會占用操作系統的資源&#xff09; 123456789#寫文件with open(rD:\Test\1.txt,w) as f: #with比<strong>try....finally<…

RUNOOB python練習題29

用來練手的python練習題其29&#xff0c;原題鏈接:python練習實例29 題干 : 給一個不多于5位的正整數&#xff0c;要求&#xff1a;一、求它是幾位數&#xff0c;二、逆序打印出各位數字。 實際這個正整數無論位數&#xff0c;在python3中都很容易實現。源代碼如下: def ent…

定時任務(Spring Cloud Task)

引入依賴 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.sprin…

P3357 最長k可重線段集問題 網絡流

P3357 最長k可重線段集問題 題目描述 給定平面 x-O-yx?O?y 上 nn 個開線段組成的集合 II&#xff0c;和一個正整數 kk 。試設計一個算法&#xff0c;從開線段集合 II 中選取出開線段集合 S\subseteq IS?I ,使得在 xx 軸上的任何一點 pp&#xff0c;SS 中與直線 xpxp 相交的開…

服務被人當肉雞了,叫一路賺錢 xig

網上看了一下&#xff0c;說有專門人研究服務 個人懷疑是阿里云內部人干的&#xff0c;因為買了服務器后&#xff0c;沒有安裝對外使用的地址性質的網站&#xff0c;IP開通了之后只有阿里的人知道&#xff0c;上面還有阿里云盾。 看了下進程地址&#xff0c;上面的啟動命令 x…

RUNOOB python練習題30 回文數

用來練手的python練習題 30。原題鏈接:python練習實例30 題干 : 一個5位數&#xff0c;判斷它是不是回文數。即12321是回文數&#xff0c;個位與萬位相同&#xff0c;十位與千位相同。 與上一個例題類似&#xff0c;判斷一個數是不是回文數&#xff0c;我們使用字符串類型更加…

高并發與負載均衡-keepalived-概念介紹

keepalived是用戶空間的程序&#xff0c;這個程序會同時在主的lvs和備用的lvs啟動 轉載于:https://www.cnblogs.com/LXL616/p/10793790.html

asp.net2.0跨域問題

什么叫跨域&#xff1f; 簡單理解就是不同服務器&#xff0c;不同域名之間的訪問。 1 如何設置asp.net web程序的跨域&#xff1f; 在web.config中添加如下代碼 1 <system.webServer> <httpProtocol> <customHeaders> <add name&qu…

RUNOOB python練習題31 根據已輸入的字符判斷星期幾

用來練手的python練習題31&#xff0c; 原題鏈接 : python練習實例31 題干 : 請輸入星期幾的第一個字母來判斷一下是星期幾&#xff0c;如果第一個字母一樣&#xff0c;則繼續判斷第二個字母。 一個條件語句練習題&#xff0c;非常簡單了可以說&#xff0c;就是把所有的條件都…

解決FTPClient上傳文件為空,顯示0字節

JAVA使用FTPClient上傳文件時總是為空&#xff0c;而使用FileZilla客戶端時卻不會。 后來查了下資料&#xff0c;FTP服務器有被動模式和主動模式。&#xff08;具體查另外資料&#xff09; 在JAVA中將FTPClient設置為被動模式即可解決問題。 import org.apache.commons.net.f…

軟件工程——結對編程第二次作業

目錄 1. 題目及要求2. 功能的設計3. GUI&#xff08;圖形用戶界面&#xff09;的設計4. 容錯機制的設計4.1 選擇運算符的容錯處理4.2 最大值和題目數輸入的容錯處理4.3 打開文件容錯處理4.4 打印的容錯處理5. 程序的運行效果6. 對領航員的評價7. 總結本次作業所開發的程序已上傳…

RUNOOB python練習題 32 列表的中括號符號小tips

用來練手的python練習題&#xff0c;原題鏈接: python練習實例32 題干: 按相反的順序輸出列表的值 拿到題目首先寫下如下代碼: a [1,2,3,4] for i in range(len(a)):print(a[len(a)-i-1])輸出結果如下: 使用一個簡單的循環就可以完成這個操作。但其實python有利用中括號操…

redis啟動后出現WARNING you have Transparent Huge Pages (THP) support enabled in your kernel問題...

問題描述&#xff1a;啟動redis后出現&#xff1a;WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command echo never > /sys/kernel/mm/trans…

Anaconda安裝第三方包(whl文件)

先說下環境 Anaconda 對應Python3.5的版本 win7,64位系統。 step1&#xff1a;下載whl文件 step2&#xff1a;打開‘Anaconda Command Prompt‘&#xff0c; 如下圖&#xff1a; step3&#xff1a;命令行窗口pip安裝&#xff0c;代碼如下&#xff1a; pip install 路徑whl…

RUNOOB python練習題33 使用join方法實現用逗號分隔列表

用來練手的python練習題&#xff0c;原題鏈接:python練習實例33 題干: 按逗號分隔列表 用逗號分隔列表&#xff0c;我們就想到了join方法。 str.join(sequence)可以用自定的str字符串分隔一個序列&#xff0c;這個序列可以是字符串&#xff0c;列表&#xff0c;元組&#xff…

Use Vim as a Python IDE

Use Vim as a Python IDE I love vim and often use it to write Python code. Here are some useful plugins and tools for building a delightful vim python environment, escpecially for Vim8: 我喜歡vim&#xff0c;經常用它來編寫Python代碼。以下是一些有用的插件和工…

sql2008“備份集中的數據庫備份與現有的xx數據庫不同”解決方法 因為是在另一臺電腦對同名數據庫做的備份,用常規方法還原,提示不是相同數據庫,不讓還原,在網上找到下面的方法解決了: 一、右擊系

sql2008“備份集中的數據庫備份與現有的xx數據庫不同”解決方法 因為是在另一臺電腦對同名數據庫做的備份&#xff0c;用常規方法還原&#xff0c;提示不是相同數據庫&#xff0c;不讓還原&#xff0c;在網上找到下面的方法解決了&#xff1a; 一、右擊系統數據庫master&…

RUNOOB python練習題 35 python print各色字體及背景

用來練手的python練習題&#xff0c;原題鏈接: python練習實例35 題干: 文本顏色設置 python中通過指令可以控制輸出的背景顏色&#xff0c;前景顏色&#xff0c;以及顯示方式。指令的語法如下: ’\033[顯示方式&#xff1b;前景色&#xff1b;背景色m 輸出字符 \033[0m’ 其…

ubuntu18.04 qemu環境搭建【學習筆記】

一、準備工具   1.1 安裝相關工具     sudo apt-get install qemu libncurses5-dev gcc-arm-linux-gnueabi build-essential 1.2 下載kernel(linux-4.0)與busybox(1.24)源碼 https://mirrors.edge.kernel.org/pub/linux/kernel/v4.x/ https://busybox.net/downloads/busy…

for else語句小tips : RUNOOB python練習題36

用來練手的python練習題&#xff0c;原題鏈接: python練習實例36 題干: 求100之內的素數 求某個范圍內的素數&#xff0c;和之前的一個例題其實是一樣的&#xff0c;上次的同類例題鏈接如下: python練習實例12 在實現題目要求時&#xff0c;這次用了for else語句&#xff0c…