当我运行应用程序并扫描IP时,由于某种原因它冻结了。此外,我不确定Yum
方法是否在运行命令后退出,或者它是否永远存在。我的目标是做一些类似$ ./inLinuxRunMe &
的东西,它在后台运行,当工作完成时,它会杀死自己。
我不认为我的Yum
方法是这样做的,因为它冻结当我开始重负荷,如播放视频等。
public class MyShell
{
public static String whatIsMyIP = null;
public static void main(String args[])
{
t = new javax.swing.Timer(10000, new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
/* Scanner: if the ip change, show the new on too. */
whatIsMyIP = MyShell.Yum("ifconfig eth0 | grep inet").toLowerCase());
/* Some logical conditions ... such as if ran then dont run, run once etc..*/
bootMe();
}
});
t.start();
/* Launch: Main application server, runs forever as server */
// MyShell.Yum("java -cp myjar.jar launch.MainApplicationAsServer");
}
/* Boot loader */
public static void bootMe() throws IOException
{
MyShell.Yum("java -cp myjar.jar launch.MainApplicationAsServer");
}
/* Question: How to optimize it? So that,
it execute the shell command and quite*/
public static String Yum(String cmds)
{
String value = "";
try
{
String cmd[] = {"/bin/sh", "-c", cmds };
Process p=Runtime.getRuntime().exec(cmd);
BufferedReader reader=new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
value += line ;
line=reader.readLine();
}
p.waitFor();
} catch(IOException e1) {
} catch(InterruptedException e2) {
}
return value;
}
}
在单独的线程中运行Yum()
方法
来自Java API:
Constructor Summary
Timer(int delay, ActionListener listener)
Creates a Timer that will notify its listeners every `delay` milliseconds.
每10秒重复一次。你需要告诉它不要重复:
public void setRepeats(boolean flag)
If flag is false, instructs the Timer to send only one action event to its listeners.
Parameters:
flag - specify false to make the timer stop after sending its first action event
:
t = new javax.swing.Timer(10000, new ActionListener() {...});
t.setRepeats(false);
t.start();