近期我遇到一个特殊的需求,需求如下:
在使用Spring Batch框架调度任务执行,期间有一个任务出现需要阻塞进程,直到有指定文件创建,创建完成后程序继续执行。
遇到这个问题,最初想使用线程方式去实现,每过五秒去文件夹下取一下文件,如果存在继续执行,但是线程阻塞会影响程序执行效率,于是查资料后发现WatchService 可以监听文件夹下文件变化,闲话少述,上代码。
private void pauseProcess() {
// 判断JOB输出参数
if (pauseList != null && !pauseList.isEmpty()) {
// 临时数据需监听的文件
Path dirPath = Paths.get("C:\\App\\Data\\SYSTEM");
String targetFileName = "JOB.STEP";
// 创建文件监听器
try (WatchService ws = FileSystems.getDefault().newWatchService()) {
//绑定文件夹监听时间
dirPath.register(ws, StandardWatchEventKinds.ENTRY_CREATE);
// 循环遍历
while (true) {
WatchKey wsKey;
try {
wsKey = ws.take();
} catch (InterruptedException e) {
System.out.println("Watch disconnect");
return;
}
// 遍历文件夹所有操作
for (WatchEvent<?> we : wsKey.pollEvents()) {
WatchEvent.Kind<?> kind = we.kind();
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
Path fileName = null;
if (we.context() instanceof Path) {
// 获取路径
fileName = dirPath.resolve((Path) we.context());
}
// 文件名比对
if (fileName.getFileName().toString().equals(targetFileName)) {
System.out.println("File already create , process continue");
return;
}
}
// 重新循环
Boolean valid = wsKey.reset();
// 无效处理
if (!valid) {
System.out.println("If key is invalid , exit a loop");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
这种情况避免了项目进行线程阻塞,使用监听方式完成了即时触发