大家好,欢迎来到IT知识分享网。
自定义JAVA 定时器
1:在web.xml文件中添加以下代码:
<filter>
<filter-name>UrlFilter</filter-name>
<filter-class>com.util.DateFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UrlFilter</filter-name>
<url-pattern>*.t</url-pattern>
</filter-mapping>
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();
}
}
}
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/20726.html