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)文章
SpringCloud搭建Eureka服務(wù)模塊的過程
Eureka在分布式系統(tǒng)中起到了連接各個微服務(wù)的紐帶作用,使得服務(wù)之間的交互變得更加靈活、可靠,本文將深入探討如何使用Spring?Cloud,逐步引導(dǎo)讀者完成Eureka服務(wù)模塊的搭建,感興趣的朋友跟隨小編一起看看吧2024-02-02
Spring-data-redis操作redis知識總結(jié)
這篇文章主要介紹了Spring-data-redis操作redis知識總結(jié),spring-data-redis是spring-data模塊的一部分,專門用來支持在spring管理項目對redis的操作。2017-04-04
springboot 設(shè)置server.port不生效的原因及解決
這篇文章主要介紹了springboot 設(shè)置server.port不生效的原因及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
記錄jdk21連接SQLServer因為TLS協(xié)議報錯問題
在使用Druid連接池連接SQL Server時,可能會遇到因TLS版本不匹配導(dǎo)致的連接失敗問題,具體表現(xiàn)為客戶端使用TLS1.3或TLS1.2,而SQL Server僅支持TLS1.0,導(dǎo)致無法建立安全連接,解決方法是修改JDK的安全配置,啟用TLS1.02024-10-10
使用spring?data的page和pageable如何實現(xiàn)分頁查詢
這篇文章主要介紹了使用spring?data的page和pageable如何實現(xiàn)分頁查詢,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
Java lambda表達式實現(xiàn)Flink WordCount過程解析
這篇文章主要介紹了Java lambda表達式實現(xiàn)Flink WordCount過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-02-02

