躺在沙滩上的小猪

快乐的每一天

应需求添加每天定时生成索引

无非就是两种方法
1:Servlet
2: Listener
 
Servlet:
package 

import org.apache.log4j.Logger;
import javax.servlet.http.HttpServlet;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 
@author martin
 
*/
public class LuceneTimerServlet extends HttpServlet {
    
private static Logger logger = Logger.getLogger(LuceneTimerServlet.class);
    
private static Timer timer;

    
static {
        timer 
= new Timer(true);
        timer.schedule(
new TimerTask() {
            
public void run() {
                System.out.println(
"开始创建索引@" + getTime(Calendar.getInstance()));
                TaxDocIndexer indexer 
= new TaxDocIndexer();
                indexer.setFirstRun(Boolean.TRUE);
                indexer.fetch();
                System.out.println(
"索引创建成功@" + getTime(Calendar.getInstance()));
            }
        },
                getFirstTime(),
                getPeriod()
        );
    }


    
public void destroy() {
        logger.debug(
"LuceneTimerServlet.destroy() begin");
        timer.cancel();
    }

    
/**
     * 从服务启动起算,第二天零时开始执行
     *
     * 
@return Timer第一次执行时间
     
*/
    
private static Date getFirstTime() {
        Calendar calendar 
= Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, 
1);
        calendar.set(Calendar.HOUR_OF_DAY, 
0);
        calendar.set(Calendar.MINUTE, 
0);
        calendar.set(Calendar.SECOND, 
0);
        logger.debug(
"开始执行时间:" + getTime(calendar));
        
return calendar.getTime();
    }

    
/**
     * 
@param calendar
     * 
@return formated time string
     
*/
    
private static String getTime(Calendar calendar) {
        
return new StringBuffer()
                .append(calendar.get(Calendar.YEAR)).append(
"")
                .append(calendar.get(Calendar.MONTH) 
+ 1).append("")
                .append(calendar.get(Calendar.DAY_OF_MONTH)).append(
"日  ")
                .append(calendar.get(Calendar.HOUR_OF_DAY)).append(
"")
                .append(calendar.get(Calendar.MINUTE)).append(
"")
                .append(calendar.get(Calendar.SECOND)).append(
"")
                .toString();
    }

    
/**
     * 计算一天的时间间隔
     * 一天24小时×每小时60分×每分60秒×1000
     *
     * 
@return 一天时间
     
*/
    
private static long getPeriod() {
        
return 86400000;
    }
}

配置web.xml
    <servlet>
        
<servlet-name>luceneTimerServlet</servlet-name>
        
<servlet-class>sompackage.servlet.LuceneTimerServlet</servlet-class>
        
<load-on-startup>1</load-on-startup>
    
</servlet>


如果采用Listener,则是:
    <listener>    
        <listener-class>sompackage.servlet.LuceneTimerServlet</listener-class>
    
</listener>

posted on 2006-03-08 12:42 martin xus 阅读(192) 评论(0)  编辑  收藏