Java WatchService是否有用于超时的内置api(若目录中未发生事件)
我想问你一个关于Java WatchService是否有用于超时的内置api(若目录中未发生事件),java,Java,我想问你一个关于WatchService的问题。因此,我有一个代码,当特定文件出现在目录中时,它正在重命名该文件。但是,如果目录中没有任何事情发生,我想设置运行WatchService的超时时间大约为2分钟 但是从我读到的。存在超时,但仅适用于启动监视目录之前的睡眠 因此,代码如下所示: try { WatchService watchService = FileSystems.getDefault().newWatchService(); Pat
WatchService
的问题。因此,我有一个代码,当特定文件出现在目录中时,它正在重命名该文件。但是,如果目录中没有任何事情发生,我想设置运行WatchService
的超时时间大约为2分钟
但是从我读到的。存在超时,但仅适用于启动监视目录之前的睡眠
因此,代码如下所示:
try {
WatchService watchService = FileSystems.getDefault().newWatchService();
Paths.get(dirPath).register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
String fileName = event.context().toString();
if (isPdfFile(fileName)) {
consumer.accept(dirPath + fileName);
return;
}
}
key.reset();
}
}
catch (IOException | InterruptedException e) {}
试试看{
WatchService WatchService=FileSystems.getDefault().newWatchService();
获取(dirPath)、注册(watchService、StandardWatchEventKinds.ENTRY\u CREATE);
监视键;
while((key=watchService.take())!=null){
for(WatchEvent事件:key.pollEvents()){
字符串文件名=event.context().toString();
if(isPdfFile(文件名)){
consumer.accept(dirPath+fileName);
返回;
}
}
键。重置();
}
}
catch(IOException | interruptedeexception e){}
或者有其他解决方法吗?如果您希望在等待需要使用的事件时超时。如果我正确理解了您的问题,您希望最多等待两分钟,在第一次匹配事件时短路。在这种情况下,您需要跟踪到目前为止实际等待的时间以及剩余时间的超时。否则,您将在每个循环中等待两分钟,或者更糟的是,在第一个不匹配的事件中退出该方法。我相信以下(未经测试的)代码应该与您想要的类似:
public static Optional<Path> watch(Path directory, Predicate<? super Path> filter)
throws IOException {
try (WatchService service = directory.getFileSystem().newWatchService()) {
directory.register(service, StandardWatchEventKinds.ENTRY_CREATE);
long timeout = TimeUnit.NANOSECONDS.convert(2L, TimeUnit.MINUTES);
while (timeout > 0L) {
final long start = System.nanoTime();
WatchKey key = service.poll(timeout, TimeUnit.NANOSECONDS);
if (key != null) {
for (WatchEvent<?> event : key.pollEvents()) {
Path context = (Path) event.context();
if (filter.test(context)) {
return Optional.of(directory.resolve(context));
}
}
key.reset();
// Accounts for the above execution time. If you don't want that you
// can move this to before the "for" loop.
timeout -= System.nanoTime() - start;
} else {
break;
}
}
} catch (InterruptedException ignore) {}
return Optional.empty();
}
另外,您的代码使用并检查是否返回
null
。该方法在等待事件可用时不应返回null
。换句话说,它返回一个WatchKey
或抛出
Path dir = ...;
watch(dir, file -> isPdfFile(file)).ifPresent(/* do something */);