java Timer 定时任务(一)

来源:互联网 发布:陈一发唱歌软件 编辑:程序博客网 时间:2024/05/17 03:13

Java调用shell 执行定时

项目中有修改一个定时任务,顺便了解了一下整个流程:
带着问题看程序:
1.Java 怎么调用shell的
2.定时是怎么起的 
3.里面一些原理性的东西有什么
模仿着项目中的程序和网上的一些例子,首先写了一个简单的程序:

ProcessBuilder proc = new ProcessBuilder("notepad.exe", "test");
try {
proc.directory(new File("D:\\"));
Process start =proc.start();
} catch (IOException e) {
e.printStackTrace();
}

        System.out.println("Task scheduled."); 

上面的程序又暴漏一些问题:
怎么知道我的命令是否成功,成功之后才继续执行
经查发现可以从下面的返回值中,来确定是否执行成功:
start.waitFor(); 0 indicates normal termination 0表示正常终止,程序改为如下:

ProcessBuilder proc = new ProcessBuilder("notepad.exe", "test");
try {
proc.directory(new File("D:\\"));
Process start =proc.start();
int waitFor = start.waitFor();
if(waitFor==0){
System.out.println(waitFor);
}

} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
此程序还会出现问题:

如果我的这个文本框不关闭,程序就一直处于阻塞状态,关都关不掉,查看api 看下对这个方法的介绍

waitFor
public abstract int waitFor()                     throws InterruptedException
causes the current thread to wait, if necessary, until the process represented by thisProcess object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

Returns:

the exit value of the process. By convention, 0 indicates normal termination


上面的大致意思就是它会是当前线程处于等待状态,如果子线程还没有终止,那么它将一直处于阻塞状态,查看我们项目中的解决方案代码改为如下:

 // new MyTimer(5); 
ProcessBuilder proc = new ProcessBuilder("notepad.exe", "test");
try {
proc.directory(new File("D:\\"));
Process start =proc.start();
// any error message?
StreamGobbler errorGobbler = new StreamGobbler(start.getErrorStream(), "ERROR");
// any output?
StreamGobbler outputGobbler = new
StreamGobbler(start.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
int waitFor = start.waitFor();
if(waitFor==0){
System.out.println(waitFor);
}

} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

class StreamGobbler extends Thread
{
InputStream is;
String type;


StreamGobbler(InputStream is, String type)
{
this.is = is;
this.type = type;
}


public void run()
{
try
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
System.out.println(line);
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}

通过网上介绍:

假设该程序不断在向标准输出流和标准错误流写数据,而JVM不读取的话,当缓冲区满之后将无法继续写入数据,最终造成阻塞在waitfor()这里。 知道问题所在,我们解决问题就好办了。查看网上说的方法多数是开两个线程在waitfor()命令之前读出窗口的标准输出缓冲区和标准错误流的内容




0 0
原创粉丝点击