FileSystemWatcher

current release 1.0.0

Overview

Simple library for watching events occurring on a file system. The events watched are CREATED, MODIFIED and DELETED. This solution is (should be) platform independent. For example, you might use this inside of your server to monitor changes in your config files.

Example

require "filesystemwatcher"

watcher = FileSystemWatcher.new()
watcher.addDirectory("/inetpub/ftproot", "*.xml")
watcher.sleepTime = 10
watcher.start { |status,file|
    if(status == FileSystemWatcher::CREATED) then
        puts "created: #{file}"
    elsif(status == FileSystemWatcher::MODIFIED) then
        puts "modified: #{file}"
    elsif(status == FileSystemWatcher::DELETED then
        puts "deleted: #{file}"
    end
}

watcher.join() # join to the thread to keep the program alive

Installation

Run 'ruby install.rb'. This will place the libraries in your ruby/lib/site_ruby directory. There are 2 files, filesystemwatcher.rb and servicestate.rb.

General Usage

  1. Create the watcher

    watcher = FileSystemWatcher.new()

  2. Tell the watcher what to watch

    watcher.addDirectory(dir[, expression])
    watcher.addFile(fileName)

    You can watch individual files or directories. If you watch a directory you can specify an ruby Dir[] expression to search that directory for. The default expression is "**/*" which means any file recursively.

  3. Optionally specify the sleep time
    The watcher uses a single thread to search for changes. This sets that threads sleep time between iterations.

    watcher.sleepTime = 10

  4. Optionally specify the threads priority

    watcher.priority = 2

  5. Optionally specify to use MD5 hashs of watched files
    Only use this if you know your files are small. This option will generate a hash of each file and only alert you of modifications if the files hash value changes.

    watcher.useMD5 = true

  6. Start Watching
    Specify the block to use when a file is created modified or deleted, as shown in the example at the top.

  7. Stop Watching

    watcher.stop()
    watcher.stopWhen { block }

    The stopWhen method lets you specify a block, and when that block evaluates to true the watcher will stop. This is provided by the servicestate mixin.

Notes

If you know that your directory contains many many files consider creating multiple FileSystemWatcher(s). Each watcher only uses 1 thread so if the number of directories is large it could slow down notifications.

Also, if you know your files are large be careful with the useMD5 option since it must read the contents of each file to generate a hash.