Spring注解配置定时任务

本文介绍如何在Spring框架中配置和使用定时任务,包括XML配置文件的设置、自动扫描配置、定时任务的启动及具体实现方式。同时,还提供了定时任务类的代码示例。

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");
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值