自定义 Java 定时器

自定义JAVA 定时器

1:在web.xml文件中添加以下代码:

  
        UrlFilter
        com.util.DateFilter
  
  
        UrlFilter
        *.t
  


2:定义filter类:

package com.util;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;


/**
 * 定时器
 */
public class DateFilter implements Filter {

	public void destroy() {
		System.out.println("close filter");
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain arg) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		req.setCharacterEncoding("utf-8");
		arg.doFilter(req, response);
	}

	public void init(FilterConfig arg0) throws ServletException {
		try {
			StartTimer();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

    /***
     * 定时执行任务
     */
	public void StartTimer() {
		try {

			//设置执行时间
	        Calendar calendar = Calendar.getInstance();
	        int year = calendar.get(Calendar.YEAR);
	        int month = calendar.get(Calendar.MONTH);
	        int day = calendar.get(Calendar.DAY_OF_MONTH);//每天
	        
	        //定制每天的11:30:00执行,
	        calendar.set(year, month, day, 11, 30, 00);
	        Date datetime = calendar.getTime();
			final Timer timer = new Timer();
			System.out.println("==定时器已经启动==");
			
				timer.scheduleAtFixedRate(new TimerTask() {
					
						public void run() {
							System.out.println("执行了定时任务..." + new Date());
							
							// timer.cancel();// 使用这个方法退出任务
						}
					
				}, datetime, 24 * 60 * 60 * 1000);// 每天推送一次24 * 60 * 60 * 1000 毫秒数
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	


}



你可能感兴趣的:(JAVA)