Posted on 2006-03-13 12:17
lubaolin 阅读(426)
评论(0) 编辑 收藏
转贴自:
http://spaces.msn.com/copperlive/blog/cns!CB05AC024B0570E0!126.entry
用Java写的定时任务 |
|
用Java定的定时任务,有的时候在执行一些后台任务时很有用
listenBean.java
import javax.servlet.*; import java.util.*; public class listenerBean implements ServletContextListener { private java.util.Timer timer = null; public void contextInitialized(ServletContextEvent event) { timer = new Timer(true); //定时器已启动 timer.schedule(new MyTask(), 0, (long) 1000*60);//定时1分钟 //已经添加任务调度表 } public void contextDestroyed(ServletContextEvent event) { timer.cancel(); //定时器销毁 } } class MyTask extends TimerTask { private static boolean isRunning = false; public void run() { if (!isRunning) { isRunning = true; //开始执行任务 //ToDo .... //执行任务完成 isRunning = false; } else { //上一次任务执行还未结束 } } }
web.xml
<web-app> <listener> <listener-class>listenerBean</listener-class> </listener> </web-app> |