为servlet项目编写定时任务

为 java servlet 项目编写servlet包括三个步骤

1、编写web.xml 的 listener 监听器配置,web.xml的侦听器会在web服务器(如tomcat)启动的时候,加载该侦听器 contextInitialized 方法

  
  
    hs.libra.core.task.CTaskListener
  


2、实现侦听器类,注意此类名称和web.xml里的一一对应关系,ServletContextListener.contextInitialized 方法会在侦听器初始化的时候调用。初始化时,创建定期器,由定时器定期执行自动任务。以下程序片段是30分钟自动执行一次。

/**servlet listener of framework core module
 * if you want to start the listener, you need to configurate it in web.xml of 
 * by fuzhou huilin corp.ltd @author lms 2016.07.25
 */
package hs.libra.core.task;

import java.util.Date;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class CTaskListener implements ServletContextListener {
	private java.util.Timer timer = null;

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		timer = new java.util.Timer(true);
		sce.getServletContext().log("initializing system core task...");
		timer.schedule(new CCoreTask(sce.getServletContext()), new Date(), 30*60*1000);
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		sce.getServletContext().log("system core auto task ended.");
		timer.cancel();
	}

}


3、编写要执行的任务,注意该类是继承了 TimerTask,注意running是static方法,保证单例执行 doTask 任务

/**frame work core work to be executed by CTaskListener
 * this task realize to GC expiry session object
 * by fuzhou huilin corp.ltd @author lms 2016.07.25
 */
package hs.libra.core.task;

import hs.libra.core.tool.CSessionUtils;

import java.util.TimerTask;

import javax.servlet.ServletContext;

public class CCoreTask extends TimerTask{
	private ServletContext sc = null;
	private static boolean running=false;

	//constructor method of CCoreTask
	public CCoreTask(ServletContext sc){
		this.sc = sc;
	}

	@Override
	public void run() {
		if (!running){
			running = true;
			this.sc.log("start running CCoreTask...");
			doTask();
			running = false;
			this.sc.log("CCoreTask runned.");
		}
	}

	private void doTask(){
		CSessionUtils.checkExpirySession();
	}
}




你可能感兴趣的:(java,autotask,TimerTask)