知乎專欄 | 多維度架構 | | | 微信號 netkiller-ebook | | | QQ群:128659835 請註明“讀者” |
配置監聽器
<listener> <listener-class>cn.netkiller.listener.NewsListener</listener-class> </listener>
實現 ServletContextListener 介面
package cn.netkiller.listener; import java.util.Timer; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.apache.log4j.Logger; public class NewsListener implements ServletContextListener { private static final Logger log = Logger.getLogger(NewsListener.class); private Timer timer = null; @Override public void contextInitialized(ServletContextEvent event) { log.info("Listener start"); timer = new Timer(true); timer.schedule(new NewsTask(event.getServletContext()), 3*1000, 5*60*1000); } @Override public void contextDestroyed(ServletContextEvent event) { if (timer != null) { timer.cancel(); } log.info("Listener end"); } }
繼承 TimerTask
package cn.netkiller.listener; import java.util.List; import java.util.TimerTask; import javax.servlet.ServletContext; import org.apache.log4j.Logger; import org.springframework.web.context.support.WebApplicationContextUtils; import cn.netkiller.service.interface.NewsService; public class NewsTask extends TimerTask{ private ServletContext context; private static final Logger log = Logger.getLogger(NewsTask.class); public NewsTask(ServletContext context) { this.context = context; } @Override public void run() { NewsService newsService = (NewsService) WebApplicationContextUtils.getWebApplicationContext(context).getBean("newsService"); try { List<cn.netkiller.listener.News> newsList = newsService.getNews(); context.setAttribute("newsList", newsList); log.info("Getting News Finished"); } catch (Exception e) { e.printStackTrace(); } } }