spring task 定時任務(wù)實現(xiàn)示例
更新時間:2017年01月19日 10:14:16 作者:簡單丶愛
本篇文章主要介紹了spring task 定時任務(wù)實現(xiàn)示例,具有一定的參考價值,有興趣的可以了解一下。
一、引入spring相關(guān)jar包:

二、在web.xml中配置spring
<listener> <description>Spring監(jiān)聽器</description> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
三、在applicationContext.xml中配置監(jiān)聽器
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd"
default-lazy-init="false">
<!-- 注解方式 -->
<context:annotation-config />
<context:component-scan base-package="com.test.task" />
<task:annotation-driven/>
<!-- XML方式 -->
<!-- <bean name="testTask" class="com.test.task.TestTask" lazy-init="false"></bean>
<task:scheduled-tasks>
<task:scheduled ref="testTask" method="print" cron="0/5 * * * * ?"/>
</task:scheduled-tasks> -->
</beans>
四、編寫實體類
package com.test.task;
import java.text.DateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class TestTask {
@Scheduled(cron = "*/5 * * * * ?")
public void print(){
String time = DateFormat.getDateTimeInstance().format(new Date());
System.out.println("定時器觸發(fā)打印"+time);
}
}
五、工程目錄:

運行結(jié)果:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
智能 AI 代碼生成工具 Cursor 安裝和使用超詳細(xì)教程
Cursor.so 是一個集成了 GPT-4 的國內(nèi)直接可以訪問的,優(yōu)秀而強大的免費代碼生成器,可以幫助你快速編寫、編輯和討論代碼,這篇文章主要介紹了智能 AI 代碼生成工具 Cursor 安裝和使用介紹,需要的朋友可以參考下
2023-05-05
詳解Java利用ExecutorService實現(xiàn)同步執(zhí)行大量線程
這篇文章主要介紹了Java利用ExecutorService實現(xiàn)同步執(zhí)行大量線程,ExecutorService可以維護(hù)我們的大量線程在操作臨界資源時的穩(wěn)定性。
2017-03-03
SpringBoot中的application.properties無法加載問題定位技巧
這篇文章主要介紹了SpringBoot中的application.properties無法加載問題定位技巧,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
2024-05-05
Spring Boot中進(jìn)行 文件上傳和 文件下載功能實現(xiàn)
開發(fā)Wb應(yīng)用時,文件上傳是很常見的一個需求,瀏覽器 通過 表單形式 將 文件 以 流的形式傳遞 給 服務(wù)器,服務(wù)器再對上傳的數(shù)據(jù)解析處理,下面將通過一個案例講解使用 SpringBoot 實現(xiàn) 文件上傳,感興趣的朋友一起看看吧
2024-07-07
Java OpenCV利用KNN算法實現(xiàn)圖像背景移除
這篇文章主要為大家介紹了Java OpenCV利用K最鄰近(KNN,K-NearestNeighbor)分類算法實現(xiàn)圖像背景移除的示例代碼,需要的可以參考一下
2022-01-01 
