Search code examples
javafilesystemwatcher

How to monitor folders using a service


I wrote a program that can monitor the folders and let me know changes in those folders. But this should run whole the day until the system is ON. This should run as a task in background(like batch process).
I am using Java WatchService for monitoring the folders.
I need some suggestions,

  1. How can make this as a service that run in background as a batch process?
  2. If i make this as service, will this effect the performance of the system? as there will be files added for every 5mins atleast in the folders.

Please suggest your ideas.

Thanks


Solution

  • You can and it should not effect your system performance when your system have enough resource.

    Steps to do that in java

    1. Write a small java class FolderMonitor to monitor a particular folder.
      1. Load a Directory File("C:\folder1")
      2. Iterate all the file and hold its last modified time in a Map map key can be a foderName+fileName and value is modified time.
      3. Check with last iteration value, if found modified or new file added do process what you need.
      4. Run the above thru ScheduledExecutorService with required interval
    2. Make FolderMonitor class into a jar.

    Make it service

    1. You can use apache's procrun or tanukisoftware service wrapper for creating a service from java executable jar
      1. Links Java Service wrapper & Apache Procrun

    Hope you can do it. All the best