/swatch

A Scala wrapper around the Java 7 WatchService

Primary LanguageScalaApache License 2.0Apache-2.0

Swatch is an (hopefully) very simple wrapper around the Java 7 WatchService API.

Binaries are available on Bintray.

Usage is pretty straightforward:

import com.mirkocaserta.swatch.Swatch._

watch("plugins", Seq(Create, Modify, Delete), println, true)

This registers a WatchService on the plugins directory and its subdirectories (because of the true value being passed to the recursive argument). The WatchService will then watch for creation, modification and deletion of files. Notifications will get sent to the println function.

If you want to (and you sure will) customize your notifications listener, it's as easy as defining a function such as:

import com.mirkocaserta.swatch.Swatch._

val listener = (event: SwatchEvent)  {
  println(s"got an event: $event")

  event match {
    case Create(path)  println(s"a file was created with path '$path'")
    case Modify(path)  println(s"a file was modified with path '$path'")
    case Delete(path)  println(s"a file was deleted with path '$path'")
  }
}

watch("plugins", Seq(Create, Modify, Delete), listener, true)

An actor wrapper is also provided. Usage looks like this:

import akka.actor.{Props, ActorSystem}
import com.mirkocaserta.swatch.Swatch._
import com.mirkocaserta.swatch.SwatchActor

val swatch = system.actorOf(Props[SwatchActor])
swatch ! Watch("plugins", Seq(Create, Modify, Delete), true)

Your sending actor will then start receiving SwatchEvent messages. You can optionally specify a different actor to be notified of SwatchEvents, via the optional listener parameter.

If you need further info, take a look at the scaladocs in the source code. I've tried to make it as estensive as possible.