因為項目需要做定時任務操作,以前接觸的知識java的timer task,感覺不是很爽,今天發現這個spring自帶的task任務比較爽,就學習了一下,
首先需要spring3以上的版本,支持注解和配置兩種形式,我就說一下配置的形式:
1.在spring的配置文件中增加紅色的部分
<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:mvc="http://www.springframework.org/schema/mvc"xmlns:task="http://www.springframework.org/schema/task"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.2.xsdhttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
2.注解掃描包<context:component-scan base-package="com.lenovo.task" />
3.配置任務
<task:scheduled-tasks> <!-- <task:scheduled ref="taskJob" method="getaccessTokenJob" cron="0 27 23/2 * * ?"/> --> <task:scheduled ref="taskJob" method="getAccessTokenJob" fixed-rate="#{1000*60*60*2}"/></task:scheduled-tasks>
這里注意支持三種屬性cron,fixed-rate,和fixed-delay
3.1.cron表達式形式
cron表達式我就不說了,你自己百度吧一大堆,但是就是注意這種方式任務執行是有固定的時間點的,比如我上邊的表達式就是23點27分執行,之后每隔2小時執行一次,不是重啟服務器,任務就立即執行。還要注意月,和星期,必須有一個是問號?
3.2fixed-rate和fixed-delay這兩個是每隔多長時間執行一次,單位是毫秒。他倆之間的區別我也不知道。有知道的說一下
4.java類如下
package com.lenovo.task;
import java.util.Date;
import org.springframework.stereotype.Service;
import com.lenovo.util.Constants;import com.lenovo.util.WxPayHelper;
@Servicepublic class TaskJob{public void getAccessTokenJob(){ WxPayHelper wxPayHelper = new WxPayHelper(); wxPayHelper.SetAppId(Constants.appId); wxPayHelper.setAppSecret(Constants.secret); wxPayHelper.setURL(Constants.accessUrl); System.out.println(Constants.accesstoken+"-----"); System.out.println(Constants.jsapi_ticket+"nidaye"); System.out.println(new Date()); try{ Constants.accesstoken = wxPayHelper.getAccessToken(); Constants.jsapi_ticket=wxPayHelper.getJsToken(Constants.accesstoken); }catch(Exception e){ e.printStackTrace(); } }}
新聞熱點
疑難解答