1、在applicationContext.xml中加入
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.3.xsd
2、创建job包,在job包下创建TaskJob类
import java.util.Date;
import org.apache.tools.ant.util.DateUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* 定时任务类
* @author zq
*
*/
@Component
public class TaskJob {
@Scheduled(cron="0/10 * * * * ?")
public void userGrade(){
System.out.println("定时器执行时间:"+DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));;
}
}
启动运行,在Console中可以看到定时器每隔10秒定时器执行一次
3、在数据库的user表中添加属性grade;//级别 total;//消费总金额
account//消费金额
在user.java 中添加三个属性的get set方法
在UserServiceImpl.java中加入以下代码
@Override
public void updateGreat() {
//会员等级列表
List<Map<String ,Object>> gradeList = new ArrayList<Map<String,Object>>();
Map<String,Object> map = new HashMap<String ,Object>();
map.put("grade", "1");
map.put("total", "0");
gradeList.add(map);
map = new HashMap<String ,Object>();
map.put("grade", "2");
map.put("total", "5000");
gradeList.add(map);
map = new HashMap<String ,Object>();
map.put("grade", "3");
map.put("total", "20000");
gradeList.add(map);
//查询符合会员等级升级条件的用户List<User>
List<User> users = userDao.findByTotal(gradeList);
if(users!=null && users.size()>0){
//更新这些用户级别加1
userDao.updateGrade(users);
}
}
在TaskJob中加入
public class TaskJob {
@Autowired
UserService userService;
@Scheduled(cron="0/10 * * * * ?")
public void userGrade(){
System.out.println("定时器执行时间:"+DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));;
userService.updateGreat();
}
在数据库中新建查询,写查询语句
select * from user
where (grade=1 and total>=5000)
or (grade=2 and total>=20000)
其实就是测试可不可以查询
4、在UserDao.xml中加入查询语句
<select id="findByTotal" parameterType="list" resultType="user">
select * from user
<where>
<foreach item="item" index="index" collection="list"
open=" ( " separator=" ) or ( " close=" ) ">
grade =#{item.grade} - 1 and total >= #{item.total}<!-- 大于和小于要用转义符 -->
</foreach>
</where>
</select>
更新语句
<updata id="updateGrade" parameterType="List"><!-- List<User>类型 -->
update user set grade = grade + 1 where id in
<foreach item="item" index="index" collection="list" open="("
separator="," close=")">
#{item.id}
</foreach>>
</updata>