博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用监听器实现Java Web的定时执行
阅读量:4120 次
发布时间:2019-05-25

本文共 1418 字,大约阅读时间需要 4 分钟。

定时器GoogleListener类:

package cn.edu.KFC.bean;import java.util.Timer;//定时器类import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import cn.edu.KFC.bean.GoogleTimer;public class GoogleListener implements ServletContextListener {	private Timer timer = null;	public void contextInitialized(ServletContextEvent event) {		// 在这里初始化监听器,在tomcat启动的时候监听器启动,可以在这里实现定时器功能		timer = new Timer(true);		// 添加日志,可在tomcat日志中查看到		event.getServletContext().log("定时器已启动");		System.out.println("定时器已启动");		// 调用GoogleTimer,0表示任务无延迟,5*1000表示每隔5秒执行任务,60*60*1000表示一个小时,24*60*60*1000表示一天。		timer.schedule(new GoogleTimer(event.getServletContext()), 0, 2 * 60 * 1000); //每2分钟执行一次GoogleTimer类		event.getServletContext().log("已经添加任务");		System.out.println("定时器已添加");	}	public void contextDestroyed(ServletContextEvent event) {// 在这里关闭监听器,所以在这里销毁定时器。		timer.cancel();		event.getServletContext().log("定时器销毁");	}}
被调用的GoogleTimer类的写法,注意extends TimerTask,并且在run()方法中执行业务:

package cn.edu.KFC.bean;import java.util.Calendar;import java.util.TimerTask;import javax.servlet.ServletContext;import cn.edu.KFC.bean.GoogleAnalytics;public class GoogleTimer extends TimerTask{	private ServletContext context = null;	GoogleAnalytics ga = new GoogleAnalytics();	public GoogleTimer(ServletContext context){		this.context = context;	}		public void run(){		ga.myTest();	}}
最后,在web.xml中设置监听器

cn.edu.KFC.bean.GoogleListener

转载地址:http://ywnpi.baihongyu.com/

你可能感兴趣的文章
Subsets 深搜
查看>>
Subsets II
查看>>
Edit Distance 字符串距离(重重)
查看>>
Gray Code 格雷码
查看>>
对话周鸿袆:从程序员创业谈起
查看>>
web.py 0.3 新手指南 - 如何用Gmail发送邮件
查看>>
web.py 0.3 新手指南 - RESTful doctesting using app.request
查看>>
web.py 0.3 新手指南 - 使用db.query进行高级数据库查询
查看>>
web.py 0.3 新手指南 - 多数据库使用
查看>>
一步步开发 Spring MVC 应用
查看>>
python: extend (扩展) 与 append (追加) 的差别
查看>>
「译」在 python 中,如果 x 是 list,为什么 x += "ha" 可以运行,而 x = x + "ha" 却抛出异常呢?...
查看>>
浅谈JavaScript的语言特性
查看>>
LeetCode第39题思悟——组合总和(combination-sum)
查看>>
LeetCode第43题思悟——字符串相乘(multiply-strings)
查看>>
LeetCode第44题思悟——通配符匹配(wildcard-matching)
查看>>
LeetCode第45题思悟——跳跃游戏(jump-game-ii)
查看>>
LeetCode第46题思悟——全排列(permutations)
查看>>
LeetCode第47题思悟—— 全排列 II(permutations-ii)
查看>>
LeetCode第48题思悟——旋转图像(rotate-image)
查看>>