Skip to content

Instantly share code, notes, and snippets.

@Julianhm9612
Created September 16, 2019 16:19
Show Gist options
  • Save Julianhm9612/a71c3609ed1ef683b25a2f97cc455f78 to your computer and use it in GitHub Desktop.
Save Julianhm9612/a71c3609ed1ef683b25a2f97cc455f78 to your computer and use it in GitHub Desktop.
package com.configuration;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import static java.nio.file.StandardWatchEventKinds.*;
import org.springframework.scheduling.annotation.Async;
public class DataSourceWatcher {
private String path;
private String file;
private Thread thread;
private WatchService watchService;
@Async
public void watchDirectory() throws IOException {
DataSourceWatcher dataSourceWatcher = new DataSourceWatcher();
watchService = FileSystems.getDefault().newWatchService();
Path pathFile = Paths.get(path);
pathFile.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
thread = new Thread(() -> {
WatchKey key = null;
try {
while ((key = watchService.take()) != null) {
Thread.sleep(500);
for (WatchEvent<?> event : key.pollEvents()) {
if(file.equals(event.context().toString())) {
//
}
}
key.reset();
}
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
} catch (Exception e) {
e.printStackTrace();
}
});
thread.start();
Runtime.getRuntime().addShutdownHook(new Thread(dataSourceWatcher::stop));
}
public void stop() {
thread.interrupt();
try {
watchService.close();
} catch (IOException e) {
System.out.println("Error cerrando el watch service " + e);
}
}
/**
* @return String return the path
*/
public String getPath() {
return path;
}
/**
* @param path the path to set
*/
public void setPath(String path) {
this.path = path;
}
/**
* @return String return the file
*/
public String getFile() {
return file;
}
/**
* @param file the file to set
*/
public void setFile(String file) {
this.file = file;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment