我想让我的程序每隔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);
}
}
}
感谢任何帮助,谢谢你。
答案 0 :(得分:4)
您应该设置一个计划任务(Windows)或cron作业(unix),每五分钟启动一次“java -jar myprogram.jar”命令。
答案 1 :(得分: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);
答案 2 :(得分:0)
如果您正在运行Linux,则可以使用cron作业计划程序来安排对程序的重复调用。其他操作系统也存在类似的调度程序。在这种情况下,我认为不需要在你的程序中实现睡眠。
答案 3 :(得分:0)