1、spring xml配置文件头部
xmlns:task="http://www.springframework.org/schema/task"
2、spring xml配置文件 xsi:schemaLocation ,版本自定义
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd
3、spring自动扫描时,包含task任务所在包
<!-- 自动扫描的包名 -->
<context:component-scan base-package="message.task" />
4、开启定时任务、设置定时任务
<task:annotation-driven />
a:配置文件配置定时任务:
<bean id="wechatTask" class="message.task.WechatTask"></bean>
<task:scheduled-tasks>
<task:scheduled ref="wechatTask" method="updateToken" cron="*/5 * * * * ?" />
<task:scheduled ref="wechatTask" method="updateJsonTemplete" cron="0 0 1 * * ?" />
</task:scheduled-tasks>
b:也可在方法名上通过注解配置:
@Scheduled(cron = "0 0 1 * * ?")//每天凌晨1点整
@Scheduled(cron = "0 30 0 * * ?")//每天凌晨0点30分
@Scheduled(cron = "0 */60 * * * ?")//1小时处理一次
eg.
@Scheduled(cron =
"*/5 * * * * ?")//每隔5秒执行一次
public
void test()
throws Exception {
System.out.println("start task ......");
}
6、写定时任务类
package message.task;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import message.entity.WeixinJsonTemplate;
import message.service.WechatJsonTmpService;
import message.service.WeixinAccService;
import message.util.LogUtil;
import message.util.TokenUtil;
@Service("wechatTask")
public class WechatTask extends SpringBeanAutowiringSupport{
@Autowired
private WeixinAccService weixinAccService;
@Autowired
private WechatJsonTmpService wechatJsonTmpService;
@Value("${accessTokenurl}")
private String access_token_url;
@Value("${jsapiticketurl}")
private String jsapi_ticket_url;
@Value("${tokenSwitch}")
private String tokenSwitch;
public void updateToken() throws Exception {
TokenUtil.getToken(access_token_url, jsapi_ticket_url, weixinAccService, weixinAccService
.findEntity(),tokenSwitch);
}
public void updateJsonTemplete() throws Exception {
List<WeixinJsonTemplate> list = wechatJsonTmpService.getWechatJsonTemplate();
if (list != null) {
for (WeixinJsonTemplate entity : list) {
entity.setId(UUID.randomUUID().toString().replace("-", ""));
}
wechatJsonTmpService.batchAddJsomTemplate(list);
} else {
LogUtil.info("it can't get template list from Tencent");
}
}
}