Skip to content

Instantly share code, notes, and snippets.

@xhanin
Created April 3, 2014 09:09
Show Gist options
  • Save xhanin/9951079 to your computer and use it in GitHub Desktop.
Save xhanin/9951079 to your computer and use it in GitHub Desktop.
Simple groovy script to watch a directory, using RESTX API
#!/bin/groovy
@Grab(group='io.restx', module='restx-common', version='0.31.1')
@Grab(group='io.restx', module='restx-barbarywatch', version='0.31.1') // useful for MacOSX only
import restx.common.MoreFiles
import restx.common.watch.FileWatchEvent
import restx.common.watch.WatcherSettings
import com.google.common.eventbus.EventBus
import com.google.common.eventbus.Subscribe
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardWatchEventKinds
import java.nio.file.WatchEvent
import java.util.concurrent.Executors
def dir = Paths.get('.') // the directory to watch
def recurse = false // should we recursively watch sub directories
def coalescePeriod = 50 // in ms, the period during which 2 similar events should be coalesced into one
def eventBus = new EventBus();
def watcherExecutor = Executors.newSingleThreadExecutor();
eventBus.register(new Object() {
@Subscribe
public void onWatchEvent(FileWatchEvent event) {
WatchEvent.Kind<?> kind = event.getKind();
Path path = event.getDir().resolve(event.getPath());
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
println "MODIFIED => $path"
} else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
println "CREATED => $path"
} else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
println "DELETED => $path"
} else {
println "unknown event kind on $path"
}
}
});
MoreFiles.watch(dir, eventBus, watcherExecutor, new WatcherSettings() {
@Override
public int coalescePeriod() {
return coalescePeriod;
}
@Override
public boolean recurse() {
return recurse;
}
})
println "Waiting for events in $dir"
System.console().readLine() // keep running and watch for changes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment