首先我讲一下我实现定时器的方法(正好在csdn看到个跟我用的一样的,就copy来):
          要运用Servlet侦听器需要实现javax.servlet.ServletContextListener接口,同时实现它的contextInitialized(ServletContextEvent   event)和contextDestroyed(ServletContextEvent   event)两个接口函数。考虑定时器有个建立和销毁的过程,看了前面两个接口函数,就不容置疑的把建立的过程置入contextInitialized,把销毁的过程置入contextDestroyed了。   
    
    我把ServletContextListener的实现类取名为ContextListener,在其内添加一个定时器,示例代码如下所示(为考虑篇幅,仅提供部分代码供读者参考):   
    
  private   java.util.Timer   timer   =   null;   
  public   void   contextInitialized(ServletContextEvent   event)   {   
  timer   =   new   java.util.Timer(true);   
  event.getServletContext().log("定时器已启动");     
  timer.schedule(new   MyTask(event.getServletContext()),   0,   60*60*1000);   
  event.getServletContext().log("已经添加任务调度表");   
  }   
  public   void   contextDestroyed(ServletContextEvent   event)   {   
  timer.cancel();   
  event.getServletContext().log("定时器销毁");   
  }     
    
    以上代码中,   timer.schedule(new   MyTask(event.getServletContext()),   0,   60*60*1000)这一行为定时器调度语句,其中MyTask是自定义需要被调度的执行任务(在我的财政数据中心项目中就是报表计算引擎入口),从java.util.TimerTask继承,下面会重点讲述,第三个参数表示每小时(即60*60*1000毫秒)被触发一次,中间参数0表示无延迟。其它代码相当简单,不再详细说明。   
    
    下面介绍MyTask的实现,上面的代码中看到了在构造MyTask时,传入了javax.servlet.ServletContext类型参数,是为记录Servlet日志方便而传入,因此需要重载MyTask的构造函数(其父类java.util.TimerTask原构造函数是没有参数的)。在timer.schedule()的调度中,设置了每小时调度一次,因此如果想实现调度任务每24小时被执行一次,还需要判断一下时钟点,以常量C_SCHEDULE_HOUR表示(晚上12点,也即0点)。同时为防止24小时执行下来,任务还未执行完(当然,一般任务是没有这么长的),避免第二次又被调度以引起执行冲突,设置了当前是否正在执行的状态标志isRunning。示例代码如下所示:   
    
  private   static   final   int   C_SCHEDULE_HOUR   =   0;   
  private   static   boolean   isRunning   =   false;   
  private   ServletContext   context   =   null;   
  public   MyTask(ServletContext   context)   {   
  this.context   =   context;   
  }   
  public   void   run()   {   
  Calendar   cal   =   Calendar.getInstance();     
  if   (!isRunning)   {     
  if   (C_SCHEDULE_HOUR   ==   cal.get(Calendar.HOUR_OF_DAY))   {     
  isRunning   =   true;     
  context.log("开始执行指定任务");   
    
  //TODO   添加自定义的详细任务,以下只是示例   
  int   i   =   0;   
  while   (i++   <   10)   {   
  context.log("已完成任务的"   +   i   +   "/"   +   10);   
  }     
  isRunning   =   false;   
  context.log("指定任务执行结束");     
  }     
  }   else   {   
  context.log("上一次任务执行还未结束");   
  }   
  }     
      
    
    上面代码中"//TODO……"之下四行是真正被调度执行的演示代码(在我的财政数据中心项目中就是报表计算过程),您可以换成自己希望执行的语句。   
    
    到这儿,ServletContextListener和MyTask的代码都已完整了。最后一步就是把ServletContextListener部署到您的Web工程中去,在您工程的web.xml配置文件中加入如下三行:   
    
    
  <listener>   
  <listener-class>com.test.ContextListener</listener-class>   
  </listener>    

 有没有哪位高手是在用这种模式实现的定时器,如果有的话,我想问的是:
     以上是定时生成的,不过现在客户要求再加一个手动生成!可现在我怎么都做不成这个
    我这边调用这个定时器主要用途是定时生成首页静态页面,而我生成静态页面的机制是用读取servlet缓冲流到io来写的!例如:
java.io.InputStream in;
URL url = new java.net.URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
//connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/4.0");
connection.connect();
in = connection.getInputStream();//问题出现处
java.io.BufferedReader breader = new BufferedReader(
new InputStreamReader(in, charset));
String currentLine;
while ((currentLine = breader.readLine()) != null) {
htmlCode += currentLine;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 得到生成html的时间差
Date after = new Date();
end = after.getTime();
ttime = end - star;
// System.out.println("执行时间:" + ttime / 1000 + "秒");
}
return htmlCode;请帮忙给个解决方案,谢谢!
有不明白的可以说,我再具体解释,在线等

解决方案 »

  1.   

    问题补充:我这边手动生成这个静态页面只能到
    in = connection.getInputStream();//问题出现处
    这句就停了,也就是in = connection.getInputStream()这个得不到内容我现在发现的一点点问题好像是这样的:这个生成静态页面的方法不能通过ie来操作,因为他本身就是获取servlet的。。
    因为我在网页后台上加按钮来调这个类不成功,而直接用空上类的main方法就可以!
      

  2.   

    我用你的代码试了一下,没发现你说的getInputStream失败啊?
      

  3.   

    我晕,我贴的只是部分代码。。我不知道你说的没失败是什么意思?莫非你还能运行?   这一块我感觉应该很多人用过吧,那段代码是用一个url生成静态页面的,全文代码是这样的import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Date; /** * @author Administrator * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public class MakeHtml {          private static long star = 0;          private static long end = 0;          private static long ttime = 0;          //返回html代码          public static String getHtmlCode(String httpUrl){          Date before = new Date();          star = before.getTime();          String htmlCode = "";          try {          InputStream   in;          URL url = new java.net.URL(httpUrl);          HttpURLConnection connection = (HttpURLConnection)url.openConnection();          connection = (HttpURLConnection) url.openConnection();          connection.setRequestProperty("User-Agent","Mozilla/4.0");          connection.connect();          in = connection.getInputStream();          java.io.BufferedReader breader = new BufferedReader(new InputStreamReader(in , "GBK"));          String currentLine;            while((currentLine=breader.readLine())!=null){          htmlCode+=currentLine;            }          } catch (Exception e) {          e.printStackTrace();          }finally{          Date after = new Date();          end = after.getTime();          ttime = end-star ;          System.out.println("执行时间:"+ttime +"秒");          }          return htmlCode;          }          //存储文件          public static synchronized void writeHtml(String filePath,String info,String flag) {          PrintWriter pw = null;          try {          File writeFile = new File(filePath);          boolean isExit = writeFile.exists();          if (isExit != true) {          writeFile.createNewFile();          } else {          if (!flag.equals("NO")) {          writeFile.delete();          writeFile.createNewFile();          }           }          pw = new PrintWriter(new FileOutputStream(filePath, true));          pw.println(info);          pw.close();          } catch (Exception ex) {          System.out.println(ex.getMessage());          }finally{          pw.close();          }          }          public static void main(String[] args) {          String url = "http://www.easydone.cn/index.htm";          writeHtml("c:/demo.htm",getHtmlCode(url),"NO");          } } 
      

  4.   


    哈哈,你贴部分代码,我当然要稍微改造一下啦,
    确实可以运行起来,将页面的html代码抓下来。你这此帖的完整代码也可以运行,没报错。建议你看看HTTPClient吧,封装的好一些,能省点事儿。
      

  5.   

    首先谢谢你的关注!
    这个程序的确可以运行的,没有问题,因为我用main方法调用成功了,
    然后把它加到定时器里去也成功了。。每过一个小时就生成静态页面了
    一切正常!所 以我没有认为我的程序有什么问题!ps:我刚贴的代码也不是我现在用的,已经改的可以封装了,不过由于用到了我们公司的util,所以贴出来给你也运行不了,就贴了个原始的类回到主题,现在问题是:我要在网站的后台加一个按钮,一点击它就可以调用这个类来生成静态页面,这样就不行了我现在的具体做法是:点击按钮,到action再调用service,而在service中我写了一个专门用来调用这个生成静态页面的类的方法这时候运行到
    in = connection.getInputStream();//问题出现处 
    这句就停下了。。不知道现在说的够不够明白。
    谢谢你的回复!