spring-task的配置及使用
阿新 • • 發佈:2018-12-25
一:在web.xml檔案中新增對容器啟動的監聽, 當容器啟動後將自動裝配application-job.xml檔案
<!-- 為上下文引數(相當於全域性變數)contextConfigLocation賦值,該配合指向application開頭的xml檔案, 定時任務的配置檔案 application-job.xml也將被讀取 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:application*.xml</param-value> </context-param> <!-- 對web容器啟動進行監聽,當容器啟動後將自動裝配上下文變數contextConfigLocation指向的配置檔案 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
二:配置application-job.xml檔案
注意在<beans>節點中配置xmlns:task和xsi:schemaLocation關於task的屬性值
<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"> <description>Job Config</description> <!-- 掃描定時器所在的包路徑 --> <context:component-scan base-package="org.power.quickbuy.job" /> <!-- 配置定時任務 --> <task:scheduled-tasks> <task:scheduled ref="alertJob" method="execute" cron="0 0 9 * * ?" /> </task:scheduled-tasks> <task:scheduled-tasks> <task:scheduled ref="statisticsJob" method="execute" cron="0 0 1 * * ?" /> </task:scheduled-tasks> </beans>
三: 建立定時任務的類及方法
注意: 類頭部需要@Service註解
package org.power.quickbuy.job; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @Service("alertJob") public class AlertJob { private static Logger logger = LoggerFactory.getLogger(AlertJob.class); public void execute(){ logger.info("當前時間:[{}]", System.currentTimeMillis()); } }