web.xml 配置定时器 详解

1.首先在web.xml中配置,监听器


	
		com.checkoo.ok.excl.TaskManager
	

2.监听器类

import java.util.Calendar;
import java.util.Timer;

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

import org.apache.commons.lang.time.DateUtils;

public class TaskManager implements ServletContextListener {

	//每天的毫秒数
	public static final long DAY = 86400000;
	//定时器
	private Timer timer;
	
	/**
	 * 在Web应用结束时停止任务
	 */
	public void contextDestroyed(ServletContextEvent sce) {
		timer.cancel();//定时器销毁

	}

	/**
	 * 在Web应用启动时初始化任务
	 */
	public void contextInitialized(ServletContextEvent sce) {
		//定义定时器
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DATE, 1);
		c.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
		timer = new Timer(true);
		LocationTask locationTask = new LocationTask();//定时执行的内容
		locationTask.setWt(sce.getServletContext().getRealPath(""));
		//timer.schedule(locationTask, c.getTime(), DAY); //定时器在每日凌晨0点执行
		timer.schedule(locationTask, 5000, 3600000); // 启动后5秒执行,后每隔1小时在执行
	}
}

3.内容类(我这里就以导出excl文件为例)

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class LocationTask extends TimerTask {
	private String wt;
	private static boolean isRunning = false;

	@Override
	public void run() {
		if (!isRunning) {
			isRunning = true;
			System.out.println("执行excle导出");
			excelPage();
			isRunning = false;
		} else {
			System.out.println("执行错误");
		}

	}

	@SuppressWarnings({ "deprecation" })
	public void excelPage() {
		List datas = DB查询;
		try {
			//第一步,创建一个webbook,对应一个Excel文件
	        HSSFWorkbook wb = new HSSFWorkbook();
	        //第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
	        HSSFSheet sheet = wb.createSheet("sheet名字");
	        //第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
	        HSSFRow row = sheet.createRow((int)0);
	        //第四步,创建单元格,并设置值表头  设置表头居中
	        HSSFCellStyle style = wb.createCellStyle();
	        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //创建一个居中格式
	        
	        HSSFCell cell = row.createCell((short)0);
	        cell.setCellValue("用户名"); cell.setCellStyle(style);
	        cell = row.createCell((short)1);
	        cell.setCellValue("密码"); cell.setCellStyle(style);
	        cell = row.createCell((short)2);
	        
	        

	        for(int i=0;i

ok,写完收工~~~


你可能感兴趣的:(web.xml 配置定时器 详解)