spring task 定時任務實現示例
更新時間:2017年01月19日 10:14:16 作者:簡單丶愛
本篇文章主要介紹了spring task 定時任務實現示例,具有一定的參考價值,有興趣的可以了解一下。
一、引入spring相關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); } }
五、工程目錄:
運行結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
springboot 設置server.port不生效的原因及解決
這篇文章主要介紹了springboot 設置server.port不生效的原因及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08記錄jdk21連接SQLServer因為TLS協(xié)議報錯問題
在使用Druid連接池連接SQL Server時,可能會遇到因TLS版本不匹配導致的連接失敗問題,具體表現為客戶端使用TLS1.3或TLS1.2,而SQL Server僅支持TLS1.0,導致無法建立安全連接,解決方法是修改JDK的安全配置,啟用TLS1.02024-10-10使用spring?data的page和pageable如何實現分頁查詢
這篇文章主要介紹了使用spring?data的page和pageable如何實現分頁查詢,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12Java lambda表達式實現Flink WordCount過程解析
這篇文章主要介紹了Java lambda表達式實現Flink WordCount過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-02-02