最近做了个啤酒厂的j2ee项目,其中有一个需求是每个月的1号,要自动生成上个月的报表,无论有人看没人看,都要自动生成。
[b]首先实现servlet监听器[/b]
[b]其次实现具体任务类[/b]
[b]最后配置一下web.xml[/b]
让其每天都检查一次,是不是每月的一号,是就生成报表
[b]首先实现servlet监听器[/b]
public class MyListener implements ServletContextListener {
private Timer timer = null;
public void contextInitialized(ServletContextEvent servletContextEvent) {
timer = new Timer(true);
//第一个参数:执行什么任务,第二个参数:什么时候开始执行,第三个参数:多久重复一次(毫秒为单位)
timer.schedule(new MyTask(), 0, 86400000);
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
timer.cancel();
}
}
[b]其次实现具体任务类[/b]
public class MyTask extends TimerTask {
public void run() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
sdf.format(date);
String currentTime = sdf.format(date);
if(currentTime.split("-")[2].equals("01")) {
doSomeThing();
}
}
private void doSomeThing() {
//To change body of created methods use File | Settings | File Templates.
}
}
[b]最后配置一下web.xml[/b]
<listener>
<listener-class>time.MyListener</listener-class>
</listener>
让其每天都检查一次,是不是每月的一号,是就生成报表