10.4.5 判断拍卖物品状态
当拍卖物品进入系统后,随着时间的流逝,拍卖物品超过了有效时间,拍卖结束,此时拍卖物品可能有两种状态:
不管是哪一种状态,这种拍卖物品状态的改变都应该由系统自动完成:系统每隔一段时间,判断系统中正在拍卖的物品是否到了拍卖期限,并修改其拍卖状态。
为了修改拍卖物品的状态,业务逻辑组件提供了一个updateWiner方法,该方法将当前时间与物品的拍卖最后期限比较,如果最后期限不晚于当前时间,则修改该物品的状态为流拍或拍卖成功。如果拍卖成功,还需要修改该物品的赢取者。该方法的代码如下。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 
 | 
 
 public void updateWiner() throws AuctionException
 {
 System.out.println("-----------------" + new Date());
 try
 {
 List<Item> itemList = itemDao.findByState(1);
 for (int i = 0; i < itemList.size(); i++)
 {
 Item item = itemList.get(i);
 if (!item.getEndtime().after(new Date()))
 {
 
 AuctionUser au = userDao.findByItemAndPrice(item.getId(),
 item.getMaxPrice());
 
 if (au != null)
 {
 
 item.setWiner(au);
 
 item.setItemState(stateDao.get(State.class, 2));
 itemDao.save(item);
 } else
 {
 
 item.setItemState(stateDao.get(State.class, 3));
 itemDao.save(item);
 }
 }
 }
 } catch (Exception ex)
 {
 log.debug(ex.getMessage());
 throw new AuctionException("根据时间来修改物品的状态、赢取者出现异常,请重试");
 }
 }
 
 | 
该方法并不由客户端直接调用,而是由任务调度来执行。Spring的任务调度机制将负责每隔一段时间自动调用该方法一次,以判断拍卖物品的状态。
系统的任务调度将让updateWiner()方法每隔一段时间执行一次,这种任务调度也可借助于Spring的任务调度机制来完成。
Spring的任务调度可简单地通过task:命令空间下的如下三个元素进行配置。
- task:scheduler:该元素用于配置一个执行任务调度的线程池。
- task:scheduled-tasks:该元素用于开启任务调度,该元素需要通过- scheduler属性指定使用哪个线程池。
- task:scheduled:该元素用于指定调度属性,比如延迟多久开始调度,每隔多长时间调度一次等。
通过这三个元素即可在Spring中配置任务调度。下面是配置该任务调度的配置片段。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | <task:scheduler
 id="myScheduler"
 pool-size="20" />
 
 <task:scheduled-tasks scheduler="myScheduler">
 <task:scheduled
 ref="auctionService"
 method="updateWiner"
 fixed-delay="86400000" />
 </task:scheduled-tasks>
 
 | 
通过如此配置,可以保证Spring 容器启动后,即建立任务调度,该任务调度每隔一段时间调用AuctionService的updateWiner()方法一次。
提示:如果读者需要了解更多关于Spring任务调度的知识,可以参考Spring项目的参考手册。
原文链接: 10.4.5 判断拍卖物品状态