欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java定时调用  

程序员文章站 2022-07-12 17:23:08
...

package com.zte.vic.common;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class AutoTimeLister implements ServletContextListener {
final LogBean log = new LogBean("auto.log");
int i=0;
private Timer timer;
public void contextDestroyed(ServletContextEvent arg0) {
if(null!=timer)
{
timer.cancel();
}

}

public void contextInitialized(ServletContextEvent arg0) {
timer=new Timer(true);

Date date=new Date();
SimpleDateFormat formatmm = new SimpleDateFormat("mm");
SimpleDateFormat formatss = new SimpleDateFormat("ss");
int mm=(60-Integer.parseInt(formatmm.format(date)))*60;
int ss=Integer.parseInt(formatss.format(date));
log.addlog("start time:"+(mm-ss));

timer.schedule(new AutoJob(),(mm-ss)*1000, 3600*1000);           //定时的调用AutoJob类中的方法

}

}




package com.zte.vic.common;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.TimerTask;

import javax.servlet.ServletContext;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

public class AutoJob extends TimerTask {


private static boolean isRunning = false;
final LogBean log = new LogBean("auto.log");
ResourceBundle bundle = ResourceBundle.getBundle("resource.auto",
new Locale(""));


@Override
public void run() {
if (!isRunning) {
HttpClient client = new HttpClient();
GetMethod method = new GetMethod(url);
try {
client.executeMethod(method);
Thread.sleep(5 * 1000);
} catch (Exception e) {
log.addlog("finally:" + e.toString());
}


}

}

 

 

 

在web.xml中加入

 <listener>
  <listener-class>
   com.zte.vic.common.AutoTimeLister
  </listener-class>
 </listener>