0

我试图让我的程序每 5 分钟运行一次。谁能告诉我如何实现这一目标?我对java相当陌生,这就是我到目前为止所拥有的。这是一个将进程打印到文本文件,然后调用该文本文件以显示其数据的程序。最好每 5 分钟运行一次。

import java.io.*;
import java.util.StringTokenizer;


public class getProcesses
{

 private String GetProcessListData()
 {
 Process p;
 Runtime runTime;
 String process = null;
 try {
 System.out.println("Allow me to hack your system and see what you have open...");

 //This will let us access windows in order to make this program possible
 runTime = Runtime.getRuntime();


 p = runTime.exec("tasklist");


 InputStream inputStream = p.getInputStream();
 InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
 BufferedReader bufferedReader = new BufferedReader(inputStreamReader);


 String line = bufferedReader.readLine();
 process = "&";
 while (line != null) {
 line = bufferedReader.readLine();
 process += line + "&";
 }

 //As we learned in class, we have to close whatever we open
 bufferedReader.close();
 inputStreamReader.close();
 inputStream.close();

 //The following output is a quote from Portal
 System.out.println("System has been modified. Thankyou and Goodbye.");
 } catch (IOException e) {
 System.out.println("Uh oh, looks like we found an IOE");
 e.printStackTrace();
 }
 return process;
 }

 private void showProcessData()
 {
 try {


 String proc = GetProcessListData();


 OutputStreamWriter outputStreamWriter =
 new OutputStreamWriter(new FileOutputStream("ProcessList.txt"));
 BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);

 StringTokenizer st = new StringTokenizer(proc, "&");

 while (st.hasMoreTokens()) {
 bufferedWriter.write(st.nextToken());  
 bufferedWriter.newLine();               
 }

 //This will close the outputStreams
 bufferedWriter.close();
 outputStreamWriter.close();

 } catch (IOException ioe) {
 ioe.printStackTrace();
 }

 }

 @SuppressWarnings("resource")
public static void main(String[] args) throws IOException
 {
 getProcesses gpl = new getProcesses();
 gpl.showProcessData();

 BufferedReader in = new BufferedReader(new FileReader("ProcessList.txt"));

 String line;
 while((line = in.readLine()) != null)
 {
     System.out.println(line);
 }
 }
}

任何帮助表示赞赏,谢谢。

4

4 回答 4

4

您应该设置一个计划任务 (Windows) 或 cron 作业 (unix) 以每五分钟启动一次命令“java -jar myprogram.jar”。

于 2013-05-14T19:11:14.340 回答
2

更简单的方法是让您的类实现 Callable(或 Runnable,如果您不希望它返回任何内容),然后使用 SchedulerExecutorService 运行它。

call() 方法应该包含将要执行的代码,并且鉴于它不允许任何参数,您应该在构造函数中提供它们。

Runnable yourInstance = new YourClass(param1, param2); // Assuming you don't want to return anything.
ScheduledExecutorService scheduledExecutor = Executors
                    .newSingleThreadScheduledExecutor();
scheduledExecutor.scheduleAtFixedRate(yourClassInstance, 0, 10000,
                    TimeUnit.MILLISECONDS);
于 2013-05-14T19:15:13.740 回答
0

如果您正在运行 Linux,您可以使用cron作业调度程序来安排程序的重复调用。其他操作系统也存在类似的调度程序。在这种情况下,我认为不需要在你的程序中实现睡眠。

于 2013-05-14T19:13:39.280 回答
0

您可以使用计时器任务

参考

例子

于 2013-05-14T19:16:02.163 回答