目录
Timer与TimerTask编写的定时器(在spring+struts2+mybatis框架下)
Timer与TimerTask编写的定时器(在spring+struts2+mybatis框架下)
代码如下
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class TimerAccounting implements ServletContextListener {
// 一天的毫秒
long daySpan = 24 * 60 * 60 * 1000;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
/**
* 定时器
*/
private Timer timer;
//初始化方法
@Override
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
// 初始定时器启动时间时分秒
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 10:42:00");
Date startTime = null;
try {
startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**
* 初始化定时器
* startTime 定时器启动时间
* daySpan 定时器延迟启动时间间隔
*/
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
costAccounting();
/* System.out.println("执行了1次"); */
}
}, startTime, daySpan);
}
//销毁定时器
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
timer.cancel();
}
public void costAccounting() {
System.out.println("执行了1次");
}
}
添加项目下WEBROOT->WEB-INF->web.xml
<!-- 要定期执行的任务 -->
<listener>
<!-- 你执行需要定时那个类路径 -->
<listener-class> com.bhlh.valueChain.action.TimerAccounting</listener-class></listener>
该定时器加载较早,继承listener可能初始化太早了,后期编写的别的功能类添加注入不进去