这里的基于服务端的意思是将该程序放到服务端,服务端发布出去后,它会自动每小时进行更新你想要更新的程序。
我这里是在服务端又新建了一个package,附上里面的代码
import java.util.Date;
import java.util.TimerTask;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Timer;
public class MyContextListener implements ServletContextListener{
private Timer timer = null;
private ServletContext context = null;
public void contextInitialized(ServletContextEvent event){
this.context = event.getServletContext();
timer = new Timer(true);
event.getServletContext().log("定时器已启动");
//每隔一小时进行更新
timer.schedule(new MyTask(this.context),0, 1000*60*60);
event.getServletContext().log("已经添加任务调度表");
}
public void contextDestroyed(ServletContextEvent event){
timer.cancel();
this.context.log("定时器销毁");
this.context = null;
}
private static class MyTask extends TimerTask{
private static boolean isRunning = false;
private ServletContext context = null;
public MyTask(ServletContext context){
this.context = context;
}
public void run(){
if(!isRunning){
isRunning = true;
context.log("开始执行指定任务");
String url = null;
url = "http://localhost:9000/ServletImple/servlet/UpdateData";
//该URL是想要进行更新的程序,当然前提是这个程序也发布出去了
try {
HttpURLConnection httpConnection = (HttpURLConnection)new URL(url).openConnection();
httpConnection.connect();//因为我想要更新的程序是以servlet发布出去的,所以这里是采用连接servlet的方式进行连接
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream(),"utf-8"));
reader.readLine();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
isRunning = false;
context.log("指定任务执行结束");
}else{
context.log("上一次任务执行还未结束");
}
}
}
}
程序很简单,就是利用了Timer和TimerTask。
注意要在web.xml中添加Listener。保证发布服务的同时定时器可以启动。
<listener>
<listener-class>mking.MyContextListener</listener-class> //该定时类的路径
</listener>
将服务发布出去,发现定时器启动了,并且每隔一小时更新一下你想要更新的程序(其实就是每隔一小时运行一下那个程序,会有你想要的结果生成)。
搞定~