1. 创建定时任务
@Component("monitorTask")
@Scope("prototype")
public class MonitorTask extends TimerTask {
private static final Logger LOGGER = LoggerFactory.getLogger(MonitorTask.class);
@Override
public void run() {
LOGGER.debug("开始检查竞拍商品....");
ProductService productService = ApplicationContextProvider.getBean(ProductService.class);
AuctionInfoService auctionInfoService = ApplicationContextProvider.getBean( AuctionInfoService.class);
OrderService orderService = ApplicationContextProvider.getBean(OrderService.class);
LOGGER.debug("productService" + productService.toString());
LOGGER.debug("auctionInfoService" + auctionInfoService.toString());
LOGGER.debug("orderService" + orderService.toString());
LOGGER.debug("结束检查竞拍商品....");
}
}
2. 实现ApplicationContextAware接口,用于获得spring容器对象
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext context;
private ApplicationContextProvider() {
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(Class<T> aClass) {
return context.getBean(aClass);
}
}
3. 实现ApplicationListener监听器。(关于Spring内置事件,请看:https://blog.youkuaiyun.com/qq_36306640/article/details/90047885)
@Component
public class InstantiationTracingBeanPostProcessor implements ApplicationListener<ContextRefreshedEvent> {
private static final Logger LOGGER = LoggerFactory.getLogger(InstantiationTracingBeanPostProcessor.class);
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("spring容器初始化完成");
}
// 判断根容器为Spring容器,防止出现调用两次的情况(mvc加载也会触发一次)
if(event.getApplicationContext().getParent() == null) {
long interval = 10 * 1000; //默认10秒
//开启线程,注册竞价物品竞价期限检测服务
LOGGER.debug("注册竞拍商品定时检测任务,间隔时间为" + interval);
MonitorTask monitorTask = new MonitorTask();
Timer timer = new Timer();
timer.schedule(monitorTask, 0, interval);
}
}
}
完成。