因为项目需要做定时任务操作,以前接触的知识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(); } }}
新闻热点
疑难解答