我使用 ScheduledThreadPoolExecutor 每 fileIntervalInSeconds 秒创建一个文件:
executorService = new ScheduledThreadPoolExecutor(1);
executorService.scheduleAtFixedRate(new Runnable()
{
@Override
public void run()
{
File file = new File(fileName);
if (file.exists())
{
Log.debug("creating new file");
openFileWriter(file);
}
}
}, fileIntervalInSeconds, fileIntervalInSeconds, TimeUnit.SECONDS);
}
private void openFileWriter() throws FileSystemNotificationException
{
// 1 - close exist writer
writer.close();
// 2 - rename to backup file name
...
// 3 - create new file
FileWriter writerFile = new FileWriter(fileName, true);
writer = new PrintWriter(writerFile);
}
我一直在向文件写入警报消息:
private synchronized void writeLine(String line) throws InterruptedException
{
writer.println(line);
}
我的问题是:
- 我如何确保在未关闭时使用 writer?(writer.close())
- 在开始写入之前,我如何等待 ScheduledThreadPoolExecutor 完成创建文件