定时器--4.9课程

本文详细介绍如何在Spring框架中配置并使用定时任务,通过示例展示了如何在applicationContext.xml中引入任务命名空间,创建定时任务类,并在数据库中进行会员等级的自动更新。文章还涉及了数据库查询和更新的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 &gt;= #{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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值