[英]how to execute a command on a timer
我编写了一个程序,该程序通过用零填充来创建任意大小的文件。 我试图通过仅每隔几秒钟刷新一次(让它持续5秒)而不是每次循环来对其进行优化。 当我尝试使用Timer时,代码为output.flush();
给我一个错误。
public static void main(String[] args) throws IOException
{
fileMaker fp = new fileMaker();
Writer output = null;
File f = new File(args[1]);
output = new BufferedWriter(new FileWriter(f, true));
output.write("0");
long size = fp.getFileSize(args[1]);
long mem = Long.parseLong(args[0]) * 1073741824; //1 Gigabyte = 1073741824 bytes
while (size < mem)
{
output.write("");
TimerTask fileProcessTask = new TimerTask()
{
@Override
public void run()
{
output.flush();
processFile();
}
};
Timer tm = new Timer();
tm.schedule(fileProcessTask, 5000L);
size = fp.getFileSize(args[1]);
double avg = (double) size / mem * 100;
System.out.println(avg + "% complete");
}
output.close();
System.out.println("Finished at " + size / 1073741824 + " Gigabyte(s)");
}
您提供的代码存在一些问题:
TimerTask
和一个新的Timer
。 您只需要一个Timer即可调度多个TimerTasks TimerTask
并使用Timer.schedule
重复执行任务(就像timer.schedule(someTimerTask, 5000, 5000);
[5s开始,每5s循环一次]) output
,可能必须将output
声明为final
"0"
和""
? 您可能只想写零字节,而不要写空字符(并且可能想直接使用FileOutputStream
) 之所以会在output.flush
出现错误,是因为一旦落入while
循环,就永远不会取消任务。
在while
循环之后,您要做的第一件事是close
输出,因此,下次由计时器运行任务时,它将关闭流,因此会看到异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.