Created
August 22, 2012 09:02
-
-
Save arvinLee/3423914 to your computer and use it in GitHub Desktop.
Servlet中的定时任务
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BackUpTableTask extends TimerTask { | |
private static Log log = LogFactory.getLog(BackUpTableTask.class); | |
private static boolean isRunning = false; | |
public void run() { | |
if (!isRunning) { | |
isRunning = true; | |
log.debug("开始执行任务..."); //开始任务 | |
//working add what you want to do | |
log.debug("执行任务完成..."); //任务完成 | |
isRunning = false; | |
} else { | |
log.debug("上一次任务执行还未结束..."); //上一次任务执行还未结束 | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TaskManager implements ServletContextListener { | |
/** | |
* 每天的毫秒数 | |
*/ | |
public static final long PERIOD_DAY = DateUtils.MILLIS_IN_DAY; | |
/** | |
* 一周内的毫秒数 | |
*/ | |
public static final long PERIOD_WEEK = PERIOD_DAY * 7; | |
/** | |
* 无延迟 | |
*/ | |
public static final long NO_DELAY = 0; | |
/** | |
* 定时器 | |
*/ | |
private Timer timer; | |
/** | |
* 在Web应用启动时初始化任务 | |
*/ | |
public void contextInitialized(ServletContextEvent event) { | |
//定义定时器 | |
timer = new Timer("数据库表备份",true); | |
//启动备份任务,每月(4个星期)执行一次 | |
timer.schedule(new BackUpTableTask(),NO_DELAY, PERIOD_WEEK * 4); | |
// timer.schedule(new BackUpTableTask(),NO_DELAY, 30000); | |
} | |
/** | |
* 在Web应用结束时停止任务 | |
*/ | |
public void contextDestroyed(ServletContextEvent event) { | |
timer.cancel(); // 定时器销毁 | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<listener> | |
<listener-class>***.TaskManager</listener-class> | |
<description>要定期执行的任务</description> | |
</listener> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment