gpt4 book ai didi

java - 如果目录中没有发生事件,WatchService 是否有任何用于超时的 api 构建

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:31:15 25 4
gpt4 key购买 nike

我想问你一个关于 WatchService 的问题。所以我有代码在目录中出现时重命名特定文件。但我想为 WatchService 设置超时,如果目录内没有任何反应,则运行 2 分钟。

但是从我读到的。有超时,但仅限于在开始监控目录之前 hibernate 。

所以代码看起来像这样:

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.poll(long,TimeUnit) .如果我正确理解你的问题,你最多需要等待两分钟,在第一个匹配事件上短路。在这种情况下,您需要跟踪到目前为止您实际等待的时间以及剩余持续时间的超时时间。否则你将在每个循环中等待两分钟,或者更糟的是在第一个不匹配的事件上退出方法。我相信以下(未经测试的)代码应该与您想要的类似:

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();
}

使用 try-with-resources 完成后,此代码还会关闭 WatchService .它还返回一个 Optional而不是使用 ConsumerPredicate 将执行与 isPdfFile(...) 相同的操作。我这样做是因为它使方法独立(这对一个例子来说很好),但如果你愿意,你可以继续使用 isPdfFileConsumer。使用该方法可能类似于:

Path dir = ...;
watch(dir, file -> isPdfFile(file)).ifPresent(/* do something */);

顺便说一句,您的代码使用 take()并检查它是否返回 null。该方法永远不会返回 null,因为它会等待事件可用。换句话说,它返回一个 WatchKey 或抛出异常。

关于java - 如果目录中没有发生事件,WatchService 是否有任何用于超时的 api 构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55059508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com