spring scheduled定时更新数据库某字段值

前两天项目中有一个功能是将到期的收费用户自动降成普通用户,这其中便需要更新数据库的字段,一开始我想的是写一个数据库脚本,让期每天定点执行, 后来发现spring 框架就可以完成定时的任务,因为对spring 不是很熟,所以在百度中搜索答案的同时发现两种办法,一种办法就是spring 整合quartz 框架,另一种办法是spring 的注解方法,而我们项目正好全是用的spring 注解方式,所以便采用了spring 的第二种方法,记录下来,以便后期使用:

以下代码转自:http://www.pm-road.com/index.php/2014/07/28/36/

1:首先要配置我们的spring.xml,在xmlns 多加下面的内容

xmlns:task=”http://www.springframework.org/schema/task”

2:然后在xsi:schemaLocation多加下面的内容

http://www.springframework.org/schema/task

http://www.springframework.org/schema/task/spring-task-3.1.xsd

3:最后是我们的task任务扫描注解,我的配置扫描位置是:项目根目录下面的task包

<task:annotation-driven/>
<context:annotation-config/>
<bean class=”org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor”/>
<context:component-scan base-package=”task”/>

4:在task包下定义接口:IVIPEndTime

package task;

public interface IVIPEndTime {
/**
* 更新收费用户到期情况
*/
public void updateVipEndTime();
}

5:增加实现方法 VIPEndTimeImpl

package task;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import service.UserManager;

@Component
public class VIPEndTimeImpl implements IVIPEndTime{

@Autowired
private UserManager userManager;//该类为user的操作类,需要自己定义
/*
* add by lipeng
* 表示每天的0点进行检查
*
*/
@Scheduled(cron=”0 0 0 * * ? “)
@Override
public void updateVipEndTime() {
userManager.updateVipWhenEndTime();
}

}

最终,就可以完成到期收费用户的自动降为普通用户了,而其中涉及了 @Scheduled(cron=”0 0 0 * * ? “)的一些用法,具体链接可参照:http://www.pm-road.com/index.php/2014/07/28/41/

猜你喜欢

转载自rqlipeng.iteye.com/blog/2155087