程式先锋Java技术维客

使用Java 程序自动启动Tomcat

十一月 11, 2008 by czl
提供一个小示例,使用Java 程序自动启动Tomcat ,原理是使用Timer + Runtime.getRuntime().exec(), 让指定时间内自动启动或者自动重启Tomcat, 不过由于时间仓促,还没有完善 ,借此抛砖引玉。
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;

public class Test
{
Timer timer;
public Test(int seconds)
{
timer = new Timer();
//这里的参数是毫秒
timer.schedule(new StartTask(), seconds * 10 * 1000, 50000); //几个参数的详细意义,你可以参考API java.util.Timer
}
public static void main(String args[])
{
new Test(5); // 5秒后运行
}

public static void startup()
{
try
{
Runtime rt = Runtime.getRuntime();
//这种启动的前提,Tomcat 必须作为windows 的服务被安装上。
Process proc = rt
.exec("D:\\java_tools\\apache-tomcat-5.5.20\\bin\\tomcat5.exe");
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<ERROR>");
while ((line = br.readLine()) != null)
System.out.println(line);
System.out.println("</ERROR>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t)
{
t.printStackTrace();
}
}

class StartTask extends TimerTask
{

public void run()
{

System.out.println("启动....");
startup();
// timer.cancel(); //结束timer中的所有任务

}

}

}



发表一条评论:
  • HTML语法: 启用

Search

 

« 九月 2010
星期日星期一星期二星期三星期四星期五星期六
   
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  
       
今天

Feeds

Navigation